Issue
If I look up what an ArrayList is and how to use it I often get confused. I get scared when I look at this for example:
new ArrayList<Element>(Arrays.asList(array))
I probably have a few gaps in my understanding of ArrayLists as a beginner. For example: What does <> stand for? Does it have special meaning? How is it internally represented? (For example: I see variables as representing a place in memory, array variables as a starting position in memory and an index of an array as a way to say how much further to go from this starting position.)
An example of where I think I need an ArrayList:
(I was trying to create an array of integers of user-input. The user-input is one integer at a time, the end condition is when the user inputs a zero endSign = 0.) Since Java doesn't allow re-sizing of an array after its creation, I searched for a solution to create an array of a dynamic length. ArrayList seems to be an option if I convert it to an array at the end, if I understand that correctly? If that's the case than it would be probably useful to make use of an ArrayList here:
private int[] userInput(int endSign){ //end-sign is 0 in this case
int validInputCounter=0;
List<int> userValues;
int value;
do{
value = readInt(); //reads integer user-input
if(value != endSign){
validInputCounter++;
userValues += value;
}else{
break;
}
}while(true);
return userValues;
}
In this code I want to return an int[] array of values that the user put in.
Solution
<> are the type arguments. They are for you to specify what type of objects will be stored in that list. You cannot use primitive types as type-arguments. You can only store objects in lists, nost primitives. Check out The Java Tutorials - Generics
An ArrayList is a Collection, and there are other types of collections (such as LinkedList and some synchronized collections. You can read about collections at The Java Tutorials - Collections). You can look into each one individually to see where they excel. There are also Maps, which you should look in to. They also dynamically grow in size, but instead of storing single objects, they store a key/pair value.
You got the main idea right: arrays dont change in size. Lists dynamically grow in size when needed.
Example of ArrayList in use:
class Demo {
public static void main(String[] args) {
ArrayList<Integer> intList = new ArrayList<>();
ArrayList<String> stringList = new ArrayList<>();
intList.add(1);
intList.add("s"); //error
stringList.add("s");
stringList.add(2); //error
}
}
I suggest reading The Java Tutorials - Autoboxing and Unboxing, since you cannot use primitive types as type arguments. The primitive 1 we added to the intList will be boxed into an object, since the list takes Integer objects.
Answered By - Vince
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.