Array of LinkedList adding new nodes - java

I've created an array (using the second answer from this method) by:
public static LinkedList<Connection>[] map;
... // later ....
map = (LinkedList<Connection>[]) new LinkedList[count];
And when I run my program, I get a NullPointerException at the line inside this for loop:
for (int j = 0; j < numOfConnections; j++) {
map[i].add(new Connection(find(s.next()), s.nextDouble(), s.next())); // NPE!
}
Can someone please tell me why this exception is thrown?

Your map is full of null when an array is created. You need to initialize each member yourself.
// Initialize.
for (int j = 0; j < numOfConnections; j++) {
// ^ I assume this means 'count' here.
map[j] = new LinkedList<Connection>();
}
// Fill
for (int j = 0; j < numOfConnections; j++) {
map[j].add(new Connection(find(s.next()), s.nextDouble(), s.next()));
// ^ BTW I think you mean `j` here.
}
(Combine the two steps if you like.)

Related

CompareTo String Array - Works Explicitly, But Not Implicitly with Variables in Loop

I'm trying to compare elements in an array. When I use a variable within a loop, I get an out of bounds error. Yet when I use explicit values in place of the variables, with the same value, it works fine.
What am I missing?
The problem line is:
int result = (myList[j]).compareToIgnoreCase(myList[j + 1]);
But if I use this, it works (values should be identical):
int result = (myList[0]).compareToIgnoreCase(myList[1]);
Have searched high and dry for this. Other posters had different issues. Would appreciate any input! Here's the example with dummy content:
public class methodSortTest
{
public static void main(String[] args)
{
// Create and load data into array
String[] myList = new String[2];
myList[0] = "Charlie";
myList[1] = "Bravo";
// Compare, positive/negative
for (int j = 0; j < myList.length; j++)
{
int result = (myList[j]).compareToIgnoreCase(myList[j + 1]);
System.out.println("Result is: " + result);
}
}
}
Try this:
change this:
for (int j = 0; j < myList.length; j++)
to this:
for (int j = 0; j < myList.length-1; j++)
problem is inside this statement:
int result = (myList[j]).compareToIgnoreCase(myList[j + 1]);
because you are accessing the j+1
Simple Helping material:
https://www.geeksforgeeks.org/understanding-array-indexoutofbounds-exception-in-java/
When j equals 1, myList[j + 1] evaluates to myList[2] which throws an ArrayIndexOutOfBoundsException. There is no item at index 2 because you have only inserted items at index 0 and 1.
Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/ArrayIndexOutOfBoundsException.html
Change your for loop from
for (int j = 0; j < myList.length; j++)
To
for (int j = 0; j < myList.length-1; j++) // note the "-1"

Why do I get an error for swap when the two values are equal in Java?

I am not sure why I get this error and do not know how to solve it. I am getting a Runtime Exception:
for(int j = 0; j < instances[maxInstance].length; j++){
centroids[orphanCentroid][j]=instances[maxInstance][j];
}
for(int j = 0; j < instances[maxInstance].length; j++){
{
double temp = centroids[maxInstance][j] ;
centroids[maxInstance][j] = centroids[orphanCentroid][j] ;
centroids[orphanCentroid][j] = temp ;
}
Error is:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at kmeans.KMeans.cluster(KMeans.java:75)
at kmeans.HW1.main(HW1.java:36)
And it happens at this line:
double temp = centroids[maxInstance][j] ;
I think you need
for(int j = 0; j < centroids[maxInstance].length; j++){
}
on your second for loop.
This can go either way, without additional information I can't really tell which one is out of bounds.
Case 1: centroids.length < maxInstance
In that case you simply can't access centroids[maxInstance], If you define them as
instances[10];
centroids[5];
int maxInstance = 5;
Potential solution: Check the size of instances.length and make sure centroids.length <= instances.length
Case 2: index j is out of bounds
Assuming centroids.length <= instances.length is true. Then
you need to check whether instances[maxInstance].length > centroids[maxInstance].length
Imaging where you define them as
new instances[maxInstance][10];
new centroids[maxInstance][5];
Then you will get java.lang.ArrayIndexOutOfBoundsException: 5 when you try to access
j=5;
centroids[maxInstance][5]
Potential solution:
for(int j = 0; j < centroids[maxInstance].length; j++){ //replace with centroids

linked list NullPointerException

I am getting NullPointerException and I don't know why.
LinkedList<Character>[][] list = new LinkedList[n][n];
for (int j = 0; j < n; ++j)
{
for (int m = 0; m < 1; m++)
{
// Here is the problem
list[j][m].add("" + (characterArray[j]));
}
}
I want to add characters from an array to the list. When I run it it says NullPointerException. I don't know how to initialize the list.
You made an array, but you failed to put any LinkedList objects into the array. You need to assign a new LinkedList to list[j][m] before you go adding characters to it.
The problem here is that you created an two dimensional array of LinkedList objects. But remember that the default value for objects in Java is null, so when the array is first created you have a 2 dimensional array of nulls. In the nested for loops you are trying to populate the linkedlist objects you think you have but you don't (Their value is null). So basically you say
null.add("" + (characterArray[j]));
obviously this creates a null pointer exception.
So the solution is to make the object (in this case make a new LinkedList object) before trying to add to it. Either by having a separate 2 nested for loops as follows:
for(int j = 0; j < n; j++)
{
for(int m = 0; m < n; m++)
{
list[j][m] = new LinkedList<Charater>();
}
}
followed normally by your code for the nested loops.
Or you can just declare the object inside your nested for loops
for (int j = 0; j < n; ++j)
{
for (int m = 0; m < 1; m++)
{
// Here is the problem
list[j][m] = new LinkedList<Charater>();
list[j][m].add("" + (characterArray[j]));
}
}

ArrayList of ArrayLists - clear function confusion

Here is a particular method I have written:
class A {
private static ArrayList<ArrayList<Integer>> inputTerms = new ArrayList<ArrayList<Integer>();
public static void method1(ArrayList<Integer> terms) {
ArrayList<Integer> clauses = new ArrayList<Integer>();
int N = terms.size();
for (int i = 0; i < N - 1; i++) {
for (int j = i + 1; j < N; j++) {
clauses.add(-terms.get(i));
clauses.add(-terms.get(j));
inputTerms.add(clauses);
clauses.clear();
}
}
}
}
This method is called multiple times from the main function.
In the end, i try to write the contents of the class variable into a file. However, when I do this, i get 0 as the contents of inputTerms. However, if i remove the clauses.clear() line, i am able to get approppriate values.
My program is such that it is vital for me to clear the clauses after adding to inputTerms. Is there any alternative to this?
**Hmmm.. I have done what you've suggested. However, I haven't quite overcome the problem. To give more background, in my main function, I have the following code:
for (int i=0; i<N-1; i++){
ArrayList<Integer> firstdiagonalTerms = new ArrayList<Integer>();
for (int j=0; j<N-i; j++){
firstdiagonalTerms.add(variable[j][i+j]);
}
method1(firstdiagonalTerms);
}
I have to call the method1 function 4 times for different combinations of 'i' and 'j'. However, I still get 0 when I use the above mentioned suggestions**
You are adding the same list and clearing it repeatedly. When you add an object to a list it copies a reference to it, not a copy of the object.
int N = terms.size();
for (int i = 0; i < N - 1; i++) {
for (int j = i + 1; j < N; j++) {
List<Integer> clauses = new ArrayList<Integer>();
clauses.add(-terms.get(i));
clauses.add(-terms.get(j));
inputTerms.add(clauses);
}
}
or
for (int i = 0, N = terms.size(); i < N - 1; i++)
for (int j = i + 1; j < N; j++)
inputTerms.add(Arrays.asList(-terms.get(i), -terms.get(j)));
Not sure i understand what you are trying to achieve, but you keep reusing the same list, which is probably not what you meant to do.
You should probably move the ArrayList<Integer> clauses = new ArrayList<Integer>(); inside the inner loop, and not call clauses.clear() at all.
When you are adding "clauses" you are adding the actual object to the arrayList, not a copy. So when you clear them all the values in the list will be removed. To get arround this, add a clone of the list:
inputTerms.add((ArrayList<Integer>) clauses.clone());
When you call clear() on list, you are updating/removing same objects (because list contains reference to objects, not copy of object). That is what causing the issue.
I think you need to do something like below. Instead of using clear(), create a new list everytime.
public static void method1 (ArrayList<Integer> terms)
{
int N = terms.size();
for (int i = 0; i<N-1; i++) {
for (int j=i+1; j<N; j++) {
ArrayList<Integer> clauses = new ArrayList<Integer>();
clauses.add(-terms.get(i));
clauses.add(-terms.get(j));
inputTerms.add(clauses);
}
}

IndexOutOfBoundsException in search for

i have a problem that return me the follow error
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 1
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.get(ArrayList.java:322)
at graphsshahar.TestDijkstra.main(TestDijkstra.java:38)
my program get a list of objects and i need to find in the list the equal to one
and then print it , here is the code
public static void main (String [] args){
System.out.println("begin");
int one = 2;
int two = 10;
List<Conniction> tempDeal = ConnictionDAO.getInstance().findPath(one, two);
List<String> oneid = new ArrayList<String>();
List<String> twoid = new ArrayList<String>();
for (int j = 1; j <= tempDeal.size(); j++) {
System.out.println("get");
if( Integer.parseInt(tempDeal.get(j).getOneid()) == one )
{
oneid.add(tempDeal.get(j).getOneid());
System.out.println(oneid.get(j));
}
}
System.out.println("end");
what should i fix ?
i dont know what is wrong with the if statement
Just change yours with this j < tempDeal.size() Numbering starts from 0 not from 1.
for (int j = 0; j < tempDeal.size(); j++) { ... }
If you would use j = 1 you are not able to get item at 0 position.
Update:
You can use also iterator like meant #AVD.
for(Conniction member: tempDeal) {
// do work
}
for (int j = 1; j < tempDeal.size(); j++)
If it is not intentional, 'j' should start from '0'
for (int j = 0; j < tempDeal.size(); j++)
List index starts with '0'
If index isn't matter then you may use iterator for loop.
for(Conniction obj: tempDeal){
if(obj!=null) {
if(Integer.parseInt(obj.getOneid())==one){
oneid.add(obj.getOneid());
}
}
}
Change this :
for (int j = 0; j < tempDeal.size(); j++) {
Lists indexes starts at 0 and ends at size() - 1
you need different counter for the oneid array. If the if-statement return false once, the next time you enter here you'll get IndexOutOfBounds.
int oneIdCount = 0;
and increment it inside the if
if( Integer.parseInt(tempDeal.get(j).getOneid()) == one )
{
oneid.add(tempDeal.get(j).getOneid());
System.out.println(oneid.get(oneIdCount));
oneIdCount++;
}
and as the above answers - start the for from int j=0
And if you want to print the last element only you can use oneid.size()-1 instead of variables.

Categories