Creating adjacency List Graph [duplicate] - java

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>();
}

Related

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

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.

ArrayList of 2 Dimensional arrays

I created a very simple program to create an ArrayList of 2 Dimensional arrays of floats.
But adding new elements in the list seems to overwrite or corrupt previous elements.
What am i doing wrong and how should this functionality be implemented?
import java.util.ArrayList;
public class multiDArrayTest {
public static void main(String[] args) {
float[][] coeff = new float[3][6];
ArrayList<float[][]> basisCoeffs;
basisCoeffs = new ArrayList<float [][]>(2);
coeff[0][0] = 0;
coeff[0][1] = 100;
coeff[0][2] = -50;
basisCoeffs.add(coeff);
coeff[0][0] = 50;
coeff[0][1] = 200;
coeff[0][2] = -400;
basisCoeffs.add(coeff);
System.out.println(basisCoeffs.get(0)[0][0]);
System.out.println(basisCoeffs.get(0)[0][1]);
System.out.println(basisCoeffs.get(0)[0][2]);
//I should get 0 100 -50 50, but i don't? Where does it go ??
System.out.println(basisCoeffs.get(1)[0][0]);
System.out.println(basisCoeffs.get(1)[0][1]);
System.out.println(basisCoeffs.get(1)[0][2]);
}
}
Here you add the array to the ArrayList, you modify that array, then you add it to the ArrayList a second time. So you have two copies of the same array in the ArrayList. I think you are confusing primitives and objects here. Arrays are objects, so they can be modified. When you get the elements out of the ArrayList, you see both elements point to that same array, which you modified, so you get the modified values back out. If you don't want that behavior, just clone the array when you add it to the ArrayList. Something like basicCoeffs.add(coeff.clone());.
What happens is that you have the coeff array with the first values, you add it to the list and everything is fine, but when you edit coeff again before adding it to the list, you also edit the one that is in position 0 of the list, since both coeff as the element in position 0 of the list they refer to the same object in Java. One option would be to create a copy and another to have the two arrays separately. Also, since I observe that your dimensions are static, you can directly add the values to the designated positions, for example:
import java.util.ArrayList;
public class multiDArrayTest {
public static void main(String[] args) {
ArrayList<float[][]> basisCoeffs = new ArrayList<float [][]>(2);
basisCoeffs.add(new float[3][6]);
basisCoeffs.add(new float[3][6]);
// First values of coeffs
basisCoeffs.get(0)[0][0] = 0;
basisCoeffs.get(0)[0][1] = 100;
basisCoeffs.get(0)[0][2] = -50;
// Second values of coeffs
basisCoeffs.get(1)[0][0] = 50;
basisCoeffs.get(1)[0][1] = 200;
basisCoeffs.get(1)[0][2] = -400;
System.out.println(basisCoeffs.get(0)[0][0]);
System.out.println(basisCoeffs.get(0)[0][1]);
System.out.println(basisCoeffs.get(0)[0][2]);
System.out.println(basisCoeffs.get(1)[0][0]);
System.out.println(basisCoeffs.get(1)[0][1]);
System.out.println(basisCoeffs.get(1)[0][2]);
}
}
Arrays in java are Mutable and pass by reference (well, pass by value of reference). this means is you change an element in an array, the reference is changed. So what do we have to do to avoid these side effects?
You can encapsulate Lists and arrays and just add a copy of objects into arrays.
if you're using Java 9 or later you can use List<float[][]> basisCoeffs = List.of(coeff) to add its Item as an immutable list.
you can read more about mutables and immutables here: Immutable class?

How to build an array of ArrayList<Integer> in Java? [duplicate]

This question already has answers here:
How can I create an Array of ArrayLists?
(20 answers)
Closed 5 years ago.
I wrote a piece of code like this
ArrayList<Integer>[]list=new ArrayList<Integer>[128];
But Eclipse says
Cannot create a generic array of ArrayList
I also tried code like this
ArrayList<Integer>[]list=(ArrayList<Integer>[])new Object[128];
But Eclipse throws exception:
[Ljava.lang.Object; cannot be cast to [Ljava.util.ArrayList;
So how can I build an array of ArrayList< Integer > ?
Thanks a lot!!
List<Integer> inp = new ArrayList<Integer>(10) to create list of integers whose size is 10.
From what I see you are trying to create an ArrayList and an Array in the same step, which is impossible.
An Arraylist differs from arrays as it is a generic class, which means it has a lot more functionality.
For example:
In your code you are trying to specify a limit to the ArrayList, ArrayLists don't have a limit, they are expandable.
You can use the .add() function to add objects to ArrayLists, and get values using the .get(int index) function.
Example code:
ArrayList<Integer> myArray = new ArrayList<Integer>(); //initialized a new arrayList
myArray.add(7); //added element 7 at index 0
myArray.add(12); // added element 12 at index 1
print(myArray.get(1)) //output 12
You can check the documentations for the ArrayList class here.
Hope that helped.
Your question isn't really clear,
but to build an array list,this code should be sufficient
ArrayList<Integer> list;
list = new ArrayList<Integer>(128);
Use this to create an ArrayList (remember, ArrayLists always have a theoretically indefinite capacity, since you can always add more elements to them - see a tutorial):
ArrayList<Integer> list = new ArrayList<>();
or this to make an array of ArrayLists:
ArrayList<Integer>[] lists = new ArrayList[128];
You will of course have to initialize your ArrayLists:
for (int i = 0; i < lists.length; i++)
lists[i] = new ArrayList<>();
Alternatively, you can create an ArrayList of ArrayLists:
ArrayList<ArrayList<Integer>> lists2 = new ArrayList<>();
for (int i = 0; i < 128; i++)
lists2.add(new ArrayList<>());

Confused about arrayList

I got this line of code when I asked the teacher for some help, but I get a redline below the last part. What could be wrong? The error message: "The type of the expression must be an array type but it resolved to ArrayList" I don't understand that, please help me to understand.
ArrayList<Point>[] touchPoints = new ArrayList<Point>()[2];
I want to have two lists to save Points. I guess I call each list like touchPoints[0]; and touchPoints[1]; !?
EDIT:
I guess I can keep it simple and just use two different List like this!?:
points1 = new ArrayList<Point>();
points2 = new ArrayList<Point>();
You have created an array of ArrayLists. This demo shows how they are used together
import java.util.ArrayList;
public class ArraysAndLists {
public static void main(String[] args) {
ArrayList<String>[] touchPoints = new ArrayList[2];
// Adding values
touchPoints[0] = new ArrayList<String>();
touchPoints[0].add("one string in the first ArrayList");
touchPoints[0].add("another string in the first ArrayList");
touchPoints[1] = new ArrayList<String>();
touchPoints[1].add("one string in the second ArrayList");
touchPoints[1].add("another string in the second ArrayList");
// touchPoints[2].add("This will give out of bounds, the array only holds two lists");
// Reading values
System.out.println(touchPoints[0].get(0)); // returns "one string in the first ArrayList"
System.out.println(touchPoints[1].get(1)); // returns "another string in the second ArrayList"
}
}
check out this Question
The component type of an array object may not be a type variable or a parameterized type, unless it is an (unbounded) wildcard type.You can declare array types whose element type is a type variable or a parameterized type, but not array objects.
You are mixing two things:
Constructing a plain array
Constructing an ArrayList
Constructing an array
A plain array is very low level. Does not have methods, and its length is fixed after you create it.
MyType[] anArray = new MyType[10];
Constructing an ArrayList
ArrayList is just an implementation of a type of Collection
Collection<MyItemType> aCollection = new ArrayList<MyItemType>();
What to do in your case?
You want a plain array of collections (which implementation is ArrayList). So:
// Create the array, use the interface in case you need to change the implementation later on
Collection<Point>[] touchPoints = (Collection<Point>) new Collection[2];
// Create each collection within that array, using the ArrayList implementation
touchPoints[0] = new ArrayList<Point>();
touchPoints[1] = new ArrayList<Point>();
How to do it better?
Try to think about why you need a plain array:
if it's just 2 elements, and always fixed, simply create two member variables.
if number can vary, just create a Collection of Collections (Collection>)
Edit given your use case:
Just create a class to hold your user input:
class UserInput {
public UserInput() {
user1TouchPoints = new ArrayList<Point>();
user2TouchPoints = new ArrayList<Point>();
}
// Add accessors and all
private Collection<Point> user1TouchPoints;
private Collection<Point> user2TouchPoints;
}
If you plan to have more players, simply use a map
class UserInput {
public UserInput() {
usersTouchPoints = new HashMap<Integer, Collection<Point>>();
}
public Collection<Point> getUserTouchPoints(Integer userId) {
return usersTouchPoints.get(userId);
}
public void addUserTouchPoints(Integer userId, Collection<Point> input) {
Collection<Point> points = usersTouchPoints.get(userId);
if (points==null) {
points = new ArrayList<Point>();
userTouchPoints.put(userId, points);
}
points.addAll(input);
}
// Maps a user ID (or index) to its touch points
// If you are using Android, use SparseArray instead of Map, this is more efficient
private Map<Integer, Collection<Point>> usersTouchPoints;
}

Regarding picking three elements from source list and adding to target list in first element itself [duplicate]

This question already exists:
Copying the data of ArrayList [closed]
Closed 9 years ago.
I an interview , question was asked let say there is an array list named A of 4 elements having values 67,34,56,78 so create another array list named B which consist of 2 elements develop a program in such a way so that first three elements of previous arraylist A should be get inserted to array list B as shown below..
Arraylist A ---> 67,34,56,78 (having size of 4)
Arraylist B ----> 67,34,56(shoud be stored in very first element of array list itself) and 56 in next element (so total size is of arraylist B is 2)
and interviwer also added that as this time it was told that arraylist A will having 4 elements initially at the starting but make another program which will be of general type means it will never be told how many elements are there in the list initially , but you have to make another list always and always pick the first three elements from the sourcelist and put in another list inside first element itself and the remaining one element of the source list as next element in the second list.
Please advise how to achieve this and how to pick the pair of 3 elements and adding it to target list.
Here it goes in the simplest way .. you may make it more efficient:
final List<String> first = new ArrayList<String>() {
{
add("67");
add("34");
add("56");
add("78");
}
};
final List<Object> second = new ArrayList<Object>();
// add first 3 elements to the second
final List<String> temp = new ArrayList<String>();
for(int i=0; i<3; i++) {
temp.add(first.get(i));
}
second.add(temp);
second.add(first.get(3));
This might be Simpler
public class SO {
public static void main(String[] args) throws IOException,
InterruptedException {
ArrayList<Integer> a = Lists.newArrayList(67, 34, 56, 78);
ArrayList<Integer> b = Lists.newArrayList();
b.addAll(a.subList(0, 3));
System.out.println(b);
}
}
Giving
[67, 34, 56]

Categories