How to initialize ArrayList with same object x times? [duplicate] - java

This question already has answers here:
How can I initialize an ArrayList with all zeroes in Java?
(5 answers)
Creating a list with repeating element
(5 answers)
Create an array with n copies of the same value/object?
(7 answers)
Closed 1 year ago.
Is there a way to fast initialize a new ArrayList object with X same objects?
Here is an example code:
private List<String> initStringArrayList(int size, String s) {
List<String> list = new ArrayList<>(size);
while (size-- > 0) {
list.add(s);
}
return list;
}
I want to have the same result, but much faster for large "size" values.
Of course, I could use this code:
private List<String> initStringArrayList(int size, String s) {
String[] array = new String[size];
Arrays.fill(array, s);
return new ArrayList<>(Arrays.asList(array));
}
But the constructor of ArrayList<>() would copy the full array instead of using it internal. That would not be acceptable.
Is there another way to do so? I need an ArrayList as result, not just a list. And it should be of any type, not just for strings.
Thank you for any answer!

Use Collections.nCopies, and copy it into an ArrayList:
private <T> List<T> initStringArrayList(int size, T s) {
return new ArrayList<>(Collections.nCopies(size, s));
}
This assumes that you really do want a mutable List at the end. If you can make do with an immutable list with the item size times, Collections.nCopies(size, s) by itself would work: it is memory-efficient, fast to allocate etc.

Related

Creating adjacency List Graph [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I am trying to create adjacency list for graph by creating array of arraylist of type edge(include source,dest,weight) as in code below :
public class Main {
static class Edge{
int s;
int d;
int wt;
Edge(int src,int des,int weight)
{
this.s = src;
this.d = des;
this.wt = weight;
}
}
public static void main(String[] args) throws Exception
{
//creating array of arraylist of type edge
ArrayList<Edge>[] graph = new ArrayList[7];
//Doubt regarding this line ,as why is it essential?
graph[0] = new ArrayList<Edge>();
//creating edge object
Edge e = new Edge(0,1,10);
//adding it into arraylist
graph[0].add(e);
}
Since I have created array of arraylist of type edge , I think I can directly add into arraylist like graph[0].add(e) without writing
graph[0] = new ArrayList();
but it isn't working without it. Why I need to give above statement when my array is of arraylist so can't I add the elements directly?
This code declares graph to be an array of 7 ArrayList, with its elements initially (as in all arrays) set to their default values - null for objects, 0 for integers, false for booleans:
ArrayList<Edge>[] graph = new ArrayList[7];
You can test it by adding this line below, or by stepping through with a debugger:
System.err.println(graph[0]); // prints "null"
Your new ArrayList[7] only reserved space for an array of (ArrayList) objects, but did not reserve space for the 7 new ArrayLists you want to add. This allows you, for instance, to add subclasses of ArrayList to your array, or leave some slots with a null value, or add the same ArrayList to several slots. All of these options can be useful in some cases, so the compiler and language do not create empty new elements unless you explicitly them to do so. I would recommend using a loop:
ArrayList<Edge>[] graph = new ArrayList<>[7];
for (int i=0; i<graph.length; i++) {
graph[i] = new ArrayList<Edge>();
}

How to get index of List Object [duplicate]

This question already has answers here:
Is there a way to access an iteration-counter in Java's for-each loop?
(16 answers)
Closed 3 years ago.
here Is Code there any way to get Index of the object from the list by calling a method in the list.
for example something like this:
class A{
String a="";
String b="";
}
List<A> alist= new ArrayList();
for (A a : alist) {
a.getIndexInList();
}
Why not use indexOf? If I recall correctly it is a built-in function of list.
List<A> alist= new ArrayList<>();
for (A a : alist) {
int index = alist.indexOf(a);
}
Only the list can give you the index. Unless the object in the array knows it's in an array it can't give you it's index.
There is no builtin solution, you can use external counter:
List<A> alist= new ArrayList();
int counter = 0;
for (A a : alist) {
// logic
counter++;
}
You could also create a map with indices as keys, something like:
IntStream.range(0, alist.size()).mapToObj(Integer::valueOf)
.collect(Collectors.toMap(
Function.identity(),
alist::get
));
but alist needs to be effectively final.

function to check string list in order give negative result [duplicate]

This question already has answers here:
What happens when an object is assigned to another object
(4 answers)
Why are two empty ArrayLists with different generic types equal?
(4 answers)
Closed 4 years ago.
I have the below function to check if it is in order
public boolean order(List<String> value) {
List<String> tmp = value;
Collections.sort(tmp);
return tmp.equals(value);
}
Test:
assertTrue(route.order(Arrays.asList("a", "s", "d")));
assertFalse(route.order(Arrays.asList("a", "k", "c")));
but fail at 2nd test, why is it not false?
Here in below line:
List<String> tmp = value;
You are just copying reference of value list argument in tmp list and hence you are sorting on tmp and indirectly value list which is one and the same.
To solve the problem change the assignment of tmp variable to:
List<String> tmp = new ArrayList<>(value);
public boolean order(List<String> value) {
List<String> tmp = new ArrayList<>(value);
Collections.sort(tmp);
return tmp.equals(value);
}
Your asserts are negative to each other.
Both arrays are sorted. Maybe you wanted ("A", "C", "B").
Also, as the fellows said before, your sort is on the original list, you have to copy it first and then to sort.

Java - turning an ArrayList to an Array [duplicate]

This question already has answers here:
make arrayList.toArray() return more specific types
(6 answers)
Closed 6 years ago.
Why does the code compile when I'm turning an ArrayList to an objectArray and does NOT compile when I'm turning an ArrayList to an stringArray (just if I mention "new String[0]")???
public static void main(String args[]) {
List<String> list = new ArrayList<>();
list.add("George");
list.add("John");
Object[] objectArray = list.toArray();
System.out.println(java.util.Arrays.toString(objectArray));
String[] stringArray = list.toArray(new String[0]);
System.out.println(java.util.Arrays.toString(objectArray));
}
To make it short, here are the signature of both methods for java.util.List
Object[] toArray()
Returns an array containing all of the elements in this list in proper sequence (from first to last element).
<T> T[] toArray(T[] a)
Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
So this is logic to get an error if you tried to store an Object[] into a String[]
You need to pass an array to specify the type. You should set the length directly, the methods can do it but you will do it easily
new String[list.length]

Java remove duplicate objects in ArrayList [duplicate]

This question already has answers here:
How do I remove repeated elements from ArrayList?
(40 answers)
Closed 9 years ago.
I have a very lengthy ArrayList comprised of objects some of them however, are undoubtedly duplicates. What is the best way of finding and removing these duplicates. Note: I have written a boolean-returning compareObjects() method.
Example
List<Item> result = new ArrayList<Item>();
Set<String> titles = new HashSet<String>();
for( Item item : originalList ) {
if( titles.add( item.getTitle() )) {
result.add( item );
}
}
Reference
Set
Java Data Structures
You mentioned writing a compareObjects method. Actually, you should override the equals method to return true when two objects are equal.
Having said that, I would just return a new list that contains unique elements from the original:
ArrayList<T> original = ...
List<T> uniques = new ArrayList<T>();
for (T element : original) {
if (!uniques.contains(element)) {
uniques.add(element);
}
}
This only works if you override equals. See this question for more information.
Hashset will remove duplicates. Example:
Set< String > uniqueItems = new HashSet< String >();
uniqueItems.add("a");
uniqueItems.add("a");
uniqueItems.add("b");
uniqueItems.add("c");
The set "uniqueItems" will contain the following : a, b, c

Categories