convert array to List using ArrayList's constructor [duplicate] - java

This question already has answers here:
Why does Arrays.asList() return its own ArrayList implementation
(6 answers)
Closed 8 years ago.
The method Arrays.asList(<T>...A) returns a List representation of A.
The returned object here is a List backed by an array, but is not an ArrayList object.
I'm looking for the differences between the object Arrays.asList() returns and an ArrayList object-- a quick source to tell these without diving into the code.
TIA.

When you call Arrays.asList it does not return a java.util.ArrayList. It returns a java.util.Arrays$ArrayList which is a fixed size list backed by the original source array. In other words, it is a view for the array exposed with Java's collection-based APIs.
String[] sourceArr = {"A", "B", "C"};
List<String> list = Arrays.asList(sourceArr);
System.out.println(list); // [A, B, C]
sourceArr[2] = ""; // changing source array changes the exposed view List
System.out.println(list); //[A, B, ]
list.set(0, "Z"); // Setting an element within the size of the source array
System.out.println(Arrays.toString(sourceArr)); //[Z, B, ]
list.set(3, "Z"); // java.lang.ArrayIndexOutOfBoundsException
System.out.println(Arrays.toString(sourceArr));
list.add("X"); //java.lang.UnsupportedOperationException
list.remove("Z"); //java.lang.UnsupportedOperationException
You cannot add elements to it and you cannot remove elements from it. If you try to add or remove elements from them you will get UnsupportedOperationException.

I'll expand my comment a little bit.
One problem that can occur if you use asList as it wasn't different from ArrayList object:
List<Object> list = Array.asList(array) ;
list.remove(0); // UnsupportedOperationException :(
Here you cannot remove the 0 element because asList returns a fixed-size list backed by the specified array. So you should do something like:
List<Object> newList = new ArrayList<>(Arrays.asList(array));
in order to make the newList modifiable.

Related

Why does Collections.ncopies return a mutable collection?

Class java.util.Collections has method nCopies().
The documentation for this method says that it returns an immutable copy of collection containing n copies of same element.
However in the below code I am able to modify the list and add a new element to the collection. How is this possible in an immutable collection?
(See line number 3, below.)
1) List<String> list = new ArrayList<String>(Collections.nCopies(5, "Some string"));
2) System.out.println(list);
3) list.add("Some other string");
4) System.out.println(list);
Because you create a new modifiable ArrayList out of the returned list?
List<String> list = new ArrayList<String>(Collections.nCopies(5, "Chinese Virus"));
this is essentially the same as
List<String> unmodifiableList = Collections.nCopies(5, "Chinese Virus");
List<String> modifiableList = new ArrayList<>(unmodifiableList);
unmodifiableList.remove(0); // will throw UnsupportedOperationException
modifiableList.remove(0); // will work without issues
In the above example modifiableList is a List containing the same elements as unmodifiableList but otherwise it's just an ordinary ArrayList that allows adding and removing elements.
You aren't modifying the collection returned from nCopies - you've created a new ArrayList and copied the contents into it. Once the copying is done, it's just a normal ArrayList, and there's no reason you won't be able to add to it.

What is the different between creating a list and inserting a value at the same time vs. in 2 steps?

I am trying to give value pre[1] to a new list by using List <Integer> list = new ArrayList(pre[1]);, but I got an empty list .
When I make this into 2 steps: first create an empty list1, then add pre[1] to my list1 , it works: list1 contains 2.
Can anyone tell me why?
I was expecting the same result.
I was thinking List <Integer> list = new ArrayList(pre[1]); is creating a list, and initializing the value to pre[1], but is not working, what is the problem??
int[] pre =new int []{1,2,3};
List <Integer> list = new ArrayList(pre[1]);
List <Integer> list1 = new ArrayList();
list1.add(pre[1]);
Please read the documentation of ArrayList's constructors.
TL;DR: There is no constructor that receives the new element(s) that the initialized ArrayList should contain.
The constructor that you're calling is the one that receives an integer as argument, which has its capacity defined according to the argument (i.e. pre[1] or 2 in your case).
The constructor of ArrayList receives initialCapacity not the element.
So in your case you are creating List with initialCapacity 2 i.e pre[1].
public ArrayList(int initialCapacity)
You may want to try List.of in java9
List.of(pre[1], pre[2]);

How to get an array list and copy elements to a new list? [duplicate]

This question already has answers here:
Java ArrayList copy
(10 answers)
Closed 5 years ago.
Here is what I have to do:
Instantiates a new list array and copies the elements of the existing list array to the new list array. The list array instance variable becomes a pointer to the new list array.
I am working with array lists and methods. I have an array list with some numbers. I took numbers from that list but I don't know how to put the numbers that I took into a new array list.
HI Please check the below code.
ArrayList<Integer> oldlist = new ArrayList<>();
oldlist.add(0);
oldlist.add(1);
oldlist.add(2);
oldlist.add(3);
ArrayList<Integer> newList = new ArrayList<>();
newList.addAll(oldlist);
This is a basic problem in programming. It is usually called "iterating" or more specifically here: "iterating through / over a collection".
A classic way in Java would be:
ArrayList<Stuff> list2 = new ArrayList<>();
for (Stuff thing : list1) list2.add(thing);
You can read the second line as: "For each thing, of class Stuff, in list1, do..." The thing you want to do, is calling addon the second list.
As of Java7 you could do:
list1.forEach((thing) -> list2.add(thing));
Or even simpler:
ArrayList<Integer> newList = new ArrayList<>(oldList);

Java/ Remove a Integer value from a list [duplicate]

This question already has answers here:
Properly removing an Integer from a List<Integer>
(8 answers)
Closed 9 years ago.
I have the following lists of Integer
whatToRemove = {2, 3, 8};
and another list
lst = {4, 6, 8}
I want to remove all whatToRemove the elements from lst.
I am trying to use lst.remove(whatToRemove.get(i)), but it is trying to remove the index, and not the value.
How can I do that?
List<Integer> whatToRemove = Arrays.asList(2, 3, 8);
List<Integer> lst = new ArrayList<Integer>(Arrays.asList(4, 6, 8));
lst.removeAll(whatToRemove);
Use iterator:
for (Iterator it=lst.iterator(); it.hasNext();) {
if (whatToRemove.contains(it.next())
it.remove();
}
if you are using Java collections to do this, you can simply call removeAll(Collection<T> o) on your first list to remove all occurences.
it would look like lst.removeAll(whatToRemove);
Alternatively you can iterate over all elements easily
for(int num : whatToRemove)
{
lst.remove(num);
}
Both are viable, if you are using arrays, you can still use the enhanced for to iterate. but removing is a different problem.
Link to Javadoc: List
This is because a List has a remove that removes an element by index and a remove that removes by object see:
http://docs.oracle.com/javase/6/docs/api/java/util/List.html#remove(int)
See how there are 2 removes :-(?
Unfortunately as your list contains integers Java thinks that you mean remove( item at) and not remove(object)
Use
Collection lst = [whatever]
lst.remove(whatToRemove.get(i))
...and then the remove should work correctly as Collection only has 1 kind of remove function (the one you want to use)
http://docs.oracle.com/javase/6/docs/api/java/util/Collection.html
Use the removeAll method on List
You can either use removeAll(), which takes an object that implements the Collection interface as the parameter like this:
list.removeAll(collection);
Or you need do some sort of iteration in order to go through all of the values as you want to remove as remove() doesn't take another list as a parameter, only an index or an object:
for(int i=0;i<whatToRemove.size();i++){
lst.remove(whatToRemove.get(i));
}
you can use removeAll(Collection c) method as shown below
lst.removeAll(whatToRemove);
Please check the sample below
List<Integer> whatToRemove = new ArrayList<Integer>();
whatToRemove.add(new Integer(2));
whatToRemove.add(new Integer(3));
whatToRemove.add(new Integer(8));
List<Integer> lst = new ArrayList<Integer>();
lst.add(new Integer(4));
lst.add(new Integer(6));
lst.add(new Integer(8));
lst.removeAll(whatToRemove);
you can refer to below URL for more details on collection and removeAll method
http://docs.oracle.com/javase/6/docs/api/java/util/Collection.html
With the list element you are going to want to remove the index of the objects within the list. For your example it will be integers obviously. To accomplish this you can used a for loop or pull each indexed object out in a manual way.
for loop - example :
for(int i = 0; i < whatToRemove.size(); i++){
whatToRemove.remove(i);
}
manual - example :
whatToRemove.remove(0);
whatToRemove.remove(1);
whatToRemove.remove(2);
This is from what I am understanding from your question that you would like to remove all the elements from your list call "whatToRemove".
Here is a link that may provide some insight into the list parameters Link - Java Object 'List'

Can I convert array of integer to List<int> or List<Integer> by Arrays.asList(array)? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Arrays.asList() not working as it should?
How to convert int[] into List<Integer> in Java?
Or must I refactor int[] to Integer[] ?
You can't have List<int>
Arrays.asList(array); will return you List with type T of (passed array)
You can have something like
Integer[] a = new Integer[]{1,2,3};
List<Integer> lst = Arrays.asList(a);
You can do this way
Integer[] a ={1,2,4};
List<Integer> intList = Arrays.asList(a);
System.out.println(intList);
Arrays.asList(array) returns a List-type view on the array. So you can use the List interface to access the values of the wrapped array of java primitives.
Now what happens if we pass an array of java Objects and an array of java primitive values? The method takes a variable number of java objects. A java primitive is not an object. Java could use autoboxing to create wrapper instances, but in this case, it will take the array itself as an java object. So we end up like this:
List<Integer> list1 = Arrays.asList(new Integer[]{1,2,3}));
List<int[]> list2 = Arrays.asList(new int[]{1,2,3}));
The first collection holds the integer values, the second one the int[] array. No autoboxing here.
So if you want to convert an array of java primitives to a List, you can't use Arrays.asList, because it will simply return a List that contains just one item: the array.
If you have a array of Integers then you can use Arrays.asList() to get a List of Integers:
Integer[] inters = new Integer[5];
List<Integer> ints = Arrays.asList(inters);
EDIT :
From the comment below from develman, java 6 has support to return List<> object for same method
OLD ANSWER :
Arrays.asList(array) returns you a java.util.List object.

Categories

Resources