I have an array name "asset" with 4 number.
I then converted it to be stored in arraylist.
Then with the arraylist copy to another array.
Is this algorithm correct?
After adding 5 the array should be able to show 5 number now
List assetList = new ArrayList();
String[] asset = {"1", "2", "3", "4"};
Collections.addAll(assetList, asset);
assetList.add("5");
String [] aListToArray = new String[assetList.size()];
aListToArray.toArray(aListToArray);
You need to change this line
aListToArray.toArray(aListToArray); // aListToArray to aListToArray itself? This would have given a compilation error
to this
assetList.toArray(aListToArray); // assetList to aListToArray is what you need.
Use just Arrays.asList(asset);
You can make some simplifications:
List assetList = new ArrayList();
String[] asset = {"1", "2", "3", "4"};
assetList.addAll(asset);
assetList.add("5");
String [] aListToArray = assetList.toArray(aListToArray);
Overall, the code is correct. However if you want to have a "dynamic array", or a collection of items that changes in size, then don't bother trying to keep something in array form. An arraylist will work fine.
Related
public static void main(String a[]){
String[] strArr = {"JAVA", "C++", "PERL", "STRUTS", "PLAY"};
List<String> strList = Arrays.asList(strArr);
System.out.println("Created List Size: "+strList.size());
System.out.println(strList);
I was looking for the explanation of the code
String[] strArr = {"JAVA", "C++", "PERL", "STRUTS", "PLAY"};
this line means that we are declaring a variable strArr of string type and in the array we are declaring 5 variables is that correct
Then I am unable to clearly understand second line
List<String> strList = Arrays.asList(strArr);
is strList an object of List<String>?
With the below code you are converting your String array to a fixed size list.
List<String> strList = Arrays.asList(strArr);
While converting an Array to a List. You can perform all operation of List to your newly created fixed size list. Exmaple Sorting a List as below.
Collection.sort(strList);
But with the above code you cannot add element into your list. While adding element in list it will throw you an exception. Sample code as below.
String[] strArr = {"JAVA", "C++", "PERL", "STRUTS", "PLAY"};
List<String> strList = Arrays.asList(strArr);
strList.add("Spring"); // This line will throw exception
System.out.println("Created List Size: "+strList.size());
System.out.println(strList);
If you want to add element to your list you have to convert your String Array to List as below.
List<String> strList = new ArrayList<String>(Arrays.asList(strArr));
Hope this will help you to understand it
Arrays.asList() is a static util for java. It creates a List copying the values from your array of strings (or any kind of primitive/object).
You can check the documentation on docs.oracle. The benefit of a List is that the size is variable, so you can add or remove elements (in short, it has no fixed size) while an array has a fixed size. This is true for List(Mutable list by default) unless you use an Immutable List which has a fixed size like an array.
Arrays.asList(T... arr) is a static method, sort of a utility, that takes an array as input and returns a List<T> backed by the input array. So, yes strList is a List.
To answer your question in the comments about "backed by":
From the Javadoc: "Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)".
So, the list is backed by the array in the sense that all changes made to the contents of the list will be reflected in the array. Example:
String[] a = new String[] {"1", "2", "3"};
List<String> l = Arrays.asList(a);
l.set(0, "0");
assert a[0] == "0";
Looked several answers on stack, tried to do it with help of this one Simple way to compare 2 ArrayLists but can't try to figure out what seems to be a problem. To summarize the code that isnt visible, I've created two arraylists that contain 4 files names. Now im trying to get the third arraylist which will contain only unique values from these two arraylists.
Example: 1st arraylist - One, Two, Three, Four
2nd arraylist - One, Three, Five, Seven
3rd arraylist - Two, Four, Five, Seven (solution arraylist)
Here is the code:
Collection<String> filesFromDir = new
ArrayList(Arrays.asList(listOfFilenamesWithNoExtension));
Collection<String> filesFromDB = new ArrayList(Arrays.asList(listOfFilesDB));
List<String> listDir = new ArrayList<String>(filesFromDir);
List<String> listDB = new ArrayList<String>(filesFromDB);
listDir.removeAll(listDB);
listDB.removeAll(listDir);
System.out.println("Unique values: ");
System.out.println(listDir);
System.out.println(listDB);
Make a duplicate of the first list and use it to removeAll from second list. Because if you remove duplicates from first list and then compare it with second list all the values will be unique as the duplicates were already removed from first list.
Collection<String> listDir = new ArrayList(Arrays.asList("1","2", "3", "4", "5", "6", "7"));
Collection<String> listDirCopy = new ArrayList<>();
listDirCopy.addAll(listDir);
Collection<String> listDB = new ArrayList(Arrays.asList("1","3", "5", "7", "9"));
List<String> destinationList = new ArrayList<String>();
listDir.removeAll(listDB);
listDB.removeAll(listDirCopy);
destinationList.addAll(listDir);
destinationList.addAll(listDB);
System.out.println(destinationList);
You shouldn't use removeAll in this case:
listDir.removeAll(listDB);
listDB.removeAll(listDir);
Because once you remove the common element 'One' from listDir, the listDB still contains it and won't be removed by listDB.removeAll(listDir) because listDir doesn't contains it.
So you end up with listDB with it's original elements.
One possible solution would be to travers both list and check if an element is common.
Despite the lists are the same size you can travers them in the same loop.
for(int i=0;i<listDB.size();i++){
if(!listDB.contains(listDir.get(i)){
resultList.add(listDir.get(i))
}
if(!listDir.contains(listDB.get(i)){
resultList.add(listDB.get(i))
}
}
Hello sorry for my beginner code here but can you maybe make the third arraylist, loop through the first and then add all the elements in the first array list. Then loop through the second list and add the elements in the 3rd array list if it does not exist or remove if it exists.
Look at the following code, hope it helps
public void sort(ArrayList<String> one, ArrayList<String> two){
ArrayList<String> three = new ArrayList<>();
three.addAll(one);
for (int i = 0; i < two.size(); i++) {
if (three.contains(two.get(i))){
three.remove(two.get(i));
}else {
three.add(two.get(i));
}
}
}
I have two lists of Strings and am removing duplicates like this:
List<String> list1 = Arrays.asList("1", "2", "3", "4");
List<String> list2 = Arrays.asList("1", "4", "5", "6");
List<String> duplicates = list1.stream().filter(s -> list2.contains(s)).collect(Collectors.toList());
list1.removeAll(duplicates);
list2.removeAll(duplicates);
So the result is:
list1 = 2, 3
list2 = 5, 6
Is there a better way to accomplish this? i.e. with fewer statements.
You can use removeAll which is defined in Collection interface.
boolean removeAll(Collection<?> c)
Removes all of this collection's elements that are also contained in
the specified collection (optional operation). After this call
returns, this collection will contain no elements in common with the
specified collection.
// init
List<String> sourceList1 = Arrays.asList("1", "2", "3", "4");
List<String> sourceList2 = Arrays.asList("1", "4", "5", "6");
// you need to create duplicate collection, because removeAll modify collection
List<String> resultList1 = new ArrayList(sourceList1);
List<String> resultList2 = new ArrayList(sourceList2);
//remove duplicates from collections
resultList1.removeAll(sourceList2); // second from first
resultList2.removeAll(sourceList1); // first from second
One of the possibilities worth considering is to create Set<String> and add these lists to it. Set allows adding only unique values to itself, it prevents adding duplicates.
The first way to use Set: Create a Set containing an intersection of both lists. Adding to new, getting rid of duplicates lists is taking place only if you checked that every object of the source is not present in previously created Set of duplicates.
Second way (only if your lists doesn't care about holding duplicates itself - for example in the first you have two times the same value existing): Create a Set for the first and for the second list, and add these lists to them and after that check for duplicates.
As I mentioned in comments I could misunderstood question and looked for "another", not for "more efficient" way of achieving what you're asking for, but maybe it could actually be helpful nonetheless.
This question already has answers here:
Initialization of an ArrayList in one line
(34 answers)
Closed 2 years ago.
I have an array of Strings and I'm looking to be able to do something along the lines of
String[] arrayOfStrings = {"this", "is", "an", "array", "of", "strings"};
List<String> listOfStrings = new ArrayList<String>( arrayOfStrings );
or
List<String> listOfStrings = new ArrayList<String>();
listOfStrings.addAll( arrayOfStrings );
I know I can do both of these if my strings are already in a collection, and also that I can iterate through the array and add them individually, but that one's a little bit messy.
Is there any way to initialise a List (or any collection for that matter) with an array?
You can use Arrays.asList method, which takes a var-args, and returns a fixed-size List backed by an array. So, you can't add any element to this list. Further, any modification done to the elements of the List will be reflected back in the array.
String[] arrayOfStrings = {"this", "is", "an", "array", "of", "strings"};
List<String> list = Arrays.asList(arrayOfStrings);
or: -
List<String> list = Arrays.asList("this", "is", "an", "array", "of", "strings");
If you want to increase the size of this list, you would have to pass it in ArrayList constructor.
List<String> list = new ArrayList<String>(Arrays.asList(arrayOfStrings));
You could use Arrays.asList() static method.
For example:
String[] arrayOfStrings = {"this", "is", "an", "array", "of", "strings"};
List<String> list = Arrays.asList(arrayOfStrings);
Note, that you create a fixed-size list "backed up by array" in such a way. If you want to be able to expand it, you'll have to do the following way:
String[] arrayOfStrings = {"this", "is", "an", "array", "of", "strings"};
List<String> list = new ArrayList<String>(Arrays.asList(arrayOfStrings));
You can use asList()
Arrays.asList(T... a)
Returns a fixed-size list backed by the specified array.
http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html
This may not fall exactly in your question, but may be worth a consideration.
List<String> list = Arrays.asList("this", "is", "an", "array", "of", "strings");
ArrayList<List<String>> arrayStringMega = new ArrayList<List<String>>(Arrays.asList(Arrays.asList("1","2","3"),Arrays.asList("2","3","4")));
I am new in Java.
Now I want to generate an ArrayList containing some values.
"Circle","blue","red","yellow","1","2","3","4"
How can I code this. I found some tutorial from internet. Only int or string accepted? How about mix? Could someone should me the code that how to do this?
Thanks!
List<String> list = Arrays.asList("Circle", "blue", "red", "yellow", "1", "2", "3", "4");
If you want to mix types, you'd need a List<Object>, and to remove the "" around the numbers. The example you show is all strings.
Once you start mixing types, you need to check the type when you're consuming the list, which may or may not be appropriate.
ArrayList<String> al = new ArrayList();
al.add("Circle");
al.add("blue");
al.add("red");
al.add("yellow");
al.add("1");
al.add("2");
al.add("3");
al.add("4");
here is a simple tutorial http://www.java-samples.com/showtutorial.php?tutorialid=234
or you can do this as well
String[] words = {"Circle", "blue", "red", "yellow", "1", "2", "3", "4"};
List<String> wordList = Arrays.asList(words);
List<Object> list = new ArrayList<Object>();
t.add("string");
t.add(5);
Or
List<Object> list = Arrays.asList("string", 5);
Or
List<Object> list = new ArrayList<Object>()
{{
add("string");
add(5);
}};
You only have one type for one list, some code for creating a list containing only Strings could be:
ArrayList<String> list = new ArrayList<String>();
//add my text as the first element
list.add("my text");
For a list with only ints you would have Integer instead of String in the example.
If you want to store "1","2","3","4" as string you could use
ArrayList<String> list = new ArrayList<String>();
Collections.addAll("Circle","blue","red","yellow","1","2","3","4");
You can not store int in any collection.However If you want to store "1","2","3","4" as Integer along with strings you could use
ArrayList<Object> list = new ArrayList<Object>();
Collections.addAll("Circle","blue","red","yellow",1,2,3,4);
Autoboxing will takecare of converting int to Integer
You many need to be extra careful while using ArrayList<Object>.
In Java, it's not recommended (although it's possible) to mix different types in a list of objects. So, for storing a list of Strings you would do this:
ArrayList<String> stringList = new ArrayList<String>();
And then add them:
stringList.add("Circle");
stringList.add("blue");
stringList.add("red");
stringList.add("yellow");
stringList.add("1");
stringList.add("2");
stringList.add("3");
stringList.add("4");