*
The moose likes Beginning Java and the fly likes Question about getting arraylist's size Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Question about getting arraylist Watch "Question about getting arraylist New topic
Author

Question about getting arraylist's size

Jon Kho
Ranch Hand

Joined: Jun 03, 2009
Posts: 54
Dear all,

I am currently thinking of how to pass the arraylist's .size value from one class to another class. As of now, I know how to do it using the code like this..

However, I am unable to edit the java's GUI OK button.. it seems that I am not allowed to do it..
OK button's code

Is there another other way to transfer the custs.size to another class within a button?

Any comments or help on this topic would be great!

Thanks.

Regards,
Jon
Jon Kho
Ranch Hand

Joined: Jun 03, 2009
Posts: 54
Dear all,

I managed to get the answer.. it's..

However, it's not working well in the logic that I want too.. for example the print results will be..

ID
2..
2..


There will be duplicates..

Any comments or help on this topic would be great!!

Regard,
Jon
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39396
    
  28
Go and read about the different interfaces in the Collections part of the Java™ Tutorials. You will see that some always permit duplicates, and some don't.
Jon Kho
Ranch Hand

Joined: Jun 03, 2009
Posts: 54
Hi Ritchie,

Thanks for the link.. I didn't knew that arraylist was under collection.. thought it was seperate methods..

anyway, I did alot of research on arraylist.. I am facing this problem that the ID being created starts at 0 instead from the last ID generated onwards.. for example..
ID
0
1
2
3
4
//When I reopen the file where I saved all the arraylist and create another ID.. It looks like this when i generate another ID
ID
0
1
2
3
4
0

The codes used..

And I tried this 2 different codes...


What i want to work..
//When I reopen the file where I saved all the arraylist and create another ID.. It looks like this when i generate another ID
ID
0
1
//2 for example this element is remove, it will generate another different ID not the reusing "2" again.. Because for every creation of new element should have a different ID..
3
4
5// This will be the next ID generated.. when you open up the file that contains the array list..
Again, any comments or help on this topic would be great!

Thanks for reading this long post..

Regards,
Jon

[edit CR]Add newlines so as to keep within width of screen.[/edit[
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39396
    
  28
If you are not in a multi-threaded application, how about a static number field in the Customer class. Increase that by 1 in the Customer constructorThere is no need to pass an id to the Customer constructor any more; it sets itself up automatically. That way of setting id numbers is very simplistic and won't work for very large counts, nor if multi-threaded.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

Campbell Ritchie wrote:
There is no need to pass an id to the Customer constructor any more; it sets itself up automatically. That way of setting id numbers is very simplistic and won't work for very large counts, nor if multi-threaded.


In a threaded environment, you can make a quick change to use volatile (atomic) variables.



Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39396
    
  28
Thank you, Henry I had forgotten about the AtomicXXX classes.
Jon Kho
Ranch Hand

Joined: Jun 03, 2009
Posts: 54
Dear all,

Thank you all for the comments!!

However I met a obstacle when i tried to use AtomicInterger.. It tells me "cannot find symbol" and "cannot find class "AtomicInteger"" which was very strange when I just copied and paste Henry's codes(i also declared "import java.util.*;")... Now I am finding out the cause of it.. Meanwhile if anyone knows what i am dealing with.. Do comment it on this topic...

EDITED(1st Time): Dear all, I found this website that tell me to put this in... "import java.util.concurrent.atomic.AtomicInteger;" which i svery strange.. and i know using the "*" would use all the methods or class under java.util... for more info about AtomicInteger refer here

EDITED(2nd Time): Hi Henry, it seems that AtomicInteger is similar to "static number field" what Ritchie mentions... When i tried to create another ID.. it will starts with 0.. so it will look like this...
ID
0
1
0// this is the one that i generate the ID after retrieving the arraylist from the file..

Thanks

Regards,
Jon
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39396
    
  28
That will probably work. Details of the class here.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39396
    
  28
No, import java.util.*; imports the classes in the java.util package. It does not import any other packages.
Jon Kho
Ranch Hand

Joined: Jun 03, 2009
Posts: 54
Dear all,

Thanks for the comments on AtomicInteger class. I learned something new today and am I right to say that it work very similar to "static number field" that allows volatile (atomic) variables ONLY which Henry mentioned earlier. Is there an class that uses non-volatile variables? I used google.com to search for such method or class but it does not give me the search results that I want.(Perhaps I am using the wrong keywords.)

I would explain the current situation that I am facing..
ID
0
1
2
3
4
//When I reopen the file where I saved all the arraylist and create another ID.. It looks like this when i generate another ID
ID
0
1
2
3
4
0// this is the new generated ID when I reopened the file


What I hope to able to achieve..
//When I reopen the file where I saved all the arraylist and create another ID.. It looks like this when i generate another ID
ID
0
1
//2 for example this element is remove, it will generate another different ID not the reusing "2" again.. Because for every creation of new element should have a different ID..
3
4
5// This will be the next ID generated.. when you first run the java program and then opening up the file that contains the array list..


Again, any comments or help on this topic would be great!

Regards,

Jon
Jon Kho
Ranch Hand

Joined: Jun 03, 2009
Posts: 54
Dear all, I have found this article on managing volatility which is good.

Now currently I am still unable to find the suitable solution on what I hope to get. But I learned about Interface Lock and Synchronized from that article.

any comments or help on this topic would be great!!

Thanks.

Regards,
Jon
Jon Kho
Ranch Hand

Joined: Jun 03, 2009
Posts: 54
Dear all,

I have spoken to my Java lecturer about this case. He told me the of concept to use another "data file" to save the last ID that is last created and using another class to extract it. As the technical details, I have to a way to do it but I am not sure where to start from.

By any chance, if someone knows of this concept do post it there while I am searching for it. It will be very helpful.

Thanks,

Regards,
Jon
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39396
    
  28
You should have got him to explain it more. It might be a text file and you write a number in it.
Jon Kho
Ranch Hand

Joined: Jun 03, 2009
Posts: 54
opps.. sorry, I guess I didn't make it clear.. He did explain to me in concept. anyway, here it goes..

Problem
Firstly, I am facing the 2 problems for generating ID when after saving the data file..
1) Using the "static int ID = 0; and ID++" method... It is Volatile, The ID will start from 0 once the program is stopped and launched again. It does not start from the last ID generated.

2) Using ArrayList's .size or .ofLastIndex to get the 'starting Int" to generate the ID but the problem comes when the arraylist is empty and there might be duplicates or reuse of the IDs.

Solution
He recommended me to take the last ID that is generated and save it to a file using another class that is just created for this function and every time the program launches. The class would automatically take the last ID that is "saved" to file(Note: the file used is a .dat file that can be opened using notepad).

I am wondering whether is it the same as the normal way to save and retrieving the "ID" aka number to the file.. I think the real problem lies in creating the codes to allow the number from the file into the class and telling the program that is the starting number to generate from.

any comments on this topic would be great!!

Regards,
Jon
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39396
    
  28
That does sound like a text file. You can set up a private static static methodNow writing the last number back to the file is quite easy with a similar method. It should be possible to write the number back only once, when the application closes, but I am not sure how to do that. Try researching shut-down hooks, and see whether they help.
Jon Kho
Ranch Hand

Joined: Jun 03, 2009
Posts: 54
Thanks for the tip Ritichie,

Using and modifying the coding that i used for other function..
I was thinking whether can I not use arraylist to extract out the one and only integer in the file?



Thanks for any comments on this topic!

Regards,
Jon
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39396
    
  28
Yes, you can have a one-member ArrayList. But why? If you only have one value, you can use a plain simple reference to point to it.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39396
    
  28
If you have a simple text file, why not use Scanner and Formatter? It is usual to use BufferedReaders and FileReaders (see this Java™ Tutorials page) rather than ObjectInputStreams.
Jon Kho
Ranch Hand

Joined: Jun 03, 2009
Posts: 54
Hi Ritchie,

Thanks for the comments. In fact, I found an example using BufferReaders and File Reader from here

Dear all,
I have modified the code to read the value from the text file first. Once clearing this, I doubt there is no problem writing the new value to the same txt file. As I would like to do things step by step..

The example code..


I am quite puzzled with one thing. Why is the private static method is above the declaration of variables..

i thought the declaration of Variables only would be at the End or start of the class, The first or the last codes of lines to execute..

for example...


Thanks for this post, any comments would be great!

Regards,
Jon
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39396
    
  28
Jon Kho wrote:In fact, I found an example using BufferReaders and File Reader from here
As I said, BufferedReader and FileReader. So why are you using object streams? I still think Formatter and Scanner are easier to use.

Agree the declaration of the AtomicInteger should precede the static method. You were correct there. And have you found out anything about shut down hooks?
Jon Kho
Ranch Hand

Joined: Jun 03, 2009
Posts: 54
Hi Ritchie,

Thanks for the reply, really appreciate it!

The main reason I would want to use Object Stream because it more easier to store data on individual elements(Object's Information) which belongs to the arraylist. The problem with using BufferReader and FileReader is that I have to put in more codes(Even though it not much different but I just want to be more "code" efficient and reducing the chances of code errors) but I like the part is that you can edit the existing information using notepad while Object Stream method can't.

However, in this example where one Integer value is needed and where "BufferReader and FileReader" (in fact i think scanner and FileReader also works) is alot better where you just need to read one line of value which I didn't thought of that until you pointed that out.

As for the shut down hooks.. I try to explain in simple terms.. You have to look what kind of application you are creating. It seems that "shut down hooks" is suitable for server type applications due to the allocation of resources for each connection to the external database. What "shut down hooks" does is to prevent shutdown of the server.

Note: I got the information from hereand here.

So I am creating a simple client application so there is no need for "shut down hooks".

As for the getting the value of Integer from the text file. I have not got any chance to try it out.. I have to restricted my time on java programming as I have another different assignment due this Friday morning. Probably I will look into this Saturday evening..

Any comments on this topic would be great!!

Thanks

Regards,
Jon

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39396
    
  28
Have another look at your 2nd link about shut-down hooks. It seems to me they are easy to use, from that article. I didn't think the first link was very good.
Jon Kho
Ranch Hand

Joined: Jun 03, 2009
Posts: 54
Dear all,

I am here to update my working code for reading the integer from the text file.. thanks Ritchie for the clues you have given!! Here is the coding...


I am just wondering... this line " int number = Integer.parseInt(custID);" would show me this message "local variable hides a field". I am not sure whether it would affect any other codes in the future but it still work as per normal for now..

Now I have two questions in my head.
1st, how do I increase the value by one.. using this? "getAndIncrement();" EDITED: I have just added this feature to the code and it seems working well.
2nd one is How do i save the last integer to the text file?

As for now, I need to get a shuteye for awhile due to lack of sleep and think about these two questions in dreamland...

any comments on this topic would be great!!

Regards,
Jon
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39396
    
  28
Your finally block might throw an Exception. If there is an Exception in the try block, you may end up with your Scanner object being null. Then you are closing that Scanner; if it is null you don't need to close it, but you will suffer a NullPointerException. I think that is less of a problem with Scanners that it used to be when we always used Readers. Somebody else may know better than me.
Answer:

change to
The thing about hiding a field can be sorted out by changing the name of the local variable. It is a warning about possibly confusing code; as you say, the code works, but it is better style to avoid the hiding.
I am pleased to see you remembered to use System.err for printing your Exception messages, but use System.err for your IllegalArgumentException too.

As for saving the last number to the text file, I still think a shutdown hook will work.
Jon Kho
Ranch Hand

Joined: Jun 03, 2009
Posts: 54
Hi all and to Ritchie too.

I have used the coding shown below to save the ID that belongs to the last element of the arraylist.. So the coding looks like this..


I am just glad that I am almost done with this function.. i also noticed there is a logic error.. for example..
1
3
4
5// I removed this last ID
next... I would get this..
1
3
4
5// this is the new generated ID..
So in theory, it is not right because every transaction is suppose have a different ID.

I was thinking to save the whole arraylist to a data file. adding another attribute call genID using boolean.. so it would show out only the ones whose ID was already given and avoiding generating the same ID created before.

anyway, later I will read up more on shutdown hooks and IllegalArgumentException ...

Any comments on this topic would be great!

Thanks.

Regards,
Jon
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39396
    
  28
Haven't got the time to read it properly, but I hope you are not catching an ArrayIndexOutOfBoundsException. That particular exception is always avoidable if you write your code correctly.
Jon Kho
Ranch Hand

Joined: Jun 03, 2009
Posts: 54
Hi Ritchie,

You got it right.. it's ArrayIndexOutOfBoundsException.. I would need this error if there is no "ArrayList's elements".. The reason why I used is because of a situation where there is no elements in the arraylist and I want to get the "ID" but unable because there is no single element to get the ID. So what I did is that I will "catch" this exception and perform the following simple codes..

Which will force it to have a value of 1 and save it into the text file.

Just curious.. Why would you want to recommend to avoid using ArrayIndexOutOfBoundsException? Would it affect the future coding?

Thanks

Regards,
Jon
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39396
    
  28
Never, never, never catch an OutOfBoundsException. If you want to check whether your List has a size of 0 you can writeYou will have to look in the List interface to see whether there are any methods which give you the size ( ) of your list.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14268
    
  21

Campbell Ritchie wrote:Never, never, never catch an OutOfBoundsException.

That's maybe phrased a bit strongly...

However, you should not use exceptions for normal flow control. Use exceptions only for handling errors, not for normal flow control.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Jon Kho
Ranch Hand

Joined: Jun 03, 2009
Posts: 54
Dear all,

Thanks for your comments..

Now I learned something new again on exceptions ...

Regards,
Jon
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question about getting arraylist's size