linked list NullPointerException - java

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

Related

How do I copy a 2d array with an unknown column size in Java?

For school work I need to write a constructor for a class that contains a 2-dimensional array of integers. The constructor copies a passed in two-dimensional array. Below is the code I have so far. The current issue I have is how to initialize the array when the "column" size of the passed in array is unknow. The issue I think I am having is when creating and initializing the array. The length of the inner and out array is unknown.
public IntMatrix (int[][] array)
{_matrix = new int [array.length][array.length-1].length];
for (int i = 0; i < array.length; i++) {
for(int j=0; j < array[i].length; j++)
_matrix[i][j]=array[i][j];
}
}
As I said in a comment, what you have is an array of arrays:
public IntMatrix(int[][] array) {
matrix = new int[array.length][];
for (int i = 0; i < array.length; i++) {
matrix[i] = new int[array[i].length];
for(int j=0; j < array[i].length; j++) {
matrix[i][j] = array[i][j];
}
}
}
You can always determine the size of an array via myArray.length, so you can allocate for each row/column as you iterate through.
A thought, however. Is it acceptable to simply store the reference to the array that you're passed ? Will it change outside your class ? If not, then that might be a simple solution if you don't have to recreate the array internally.

Java - Filling multidimensional (2d) ArrayList like a 2d array

A while ago before I got used to object object oriented programming I created a basic TicTacToe game and to create the board I used an array.
The code is a complete mess because I didn't properly understand how to use objects, but I did initialize the board correctly:
char[][] board = new char[3][3];
for (int i = 0; i < board.length; i++){
for (int j = 0; j < board[i].length; j++){
board[i][j] = '[]' //or something like that...don't remember exactly
}
}
My question is how would you this with an ArrayList?
ArrayList <ArrayList<Character>> board = new ArrayList(); // this initialization is not
// wrong using Java 8 but for earlier versions you would need to state the type on both
//sides of the equal sign not just the left
for (int i = 0; i < board.size(); i++){
for (int j = 0; j < board.get(i).size(); j++){
board.get(i).get(j).add('[]');
}
}
but that does not work.
It does not have to be exactly like this, I just generally want to understand how to handle multidimensional ArrayLists.
-thanks
Unlike arrays, you can't initialize an entire ArrayList directly. You can specify the expected size beforehand (this helps performance when you are using very large lists, so it is a good practice to do it always).
int boardSize = 3;
ArrayList<ArrayList<Character>> board = new ArrayList<ArrayList<Character>>(boardSize);
for (int i = 0; i < boardSize; i++) {
board.add(new ArrayList<Character>(boardSize));
for (int j = 0; j < boardSize; j++){
board.get(i).add('0');
}
}
The main difference is that in your original code you had a multi-dimensional array of primitives (in this case, char) and all you had to do was assign a new primitive value to each slot in the array.
However what you want now is an ArrayList of (ArrayList of Character). When you create the ArrayList it is empty. In order to procede you are going to need to fill it with several (ArrayList of Character) before you can begin to start adding Characters themselves.
So for example,
ArrayList <ArrayList<Character>> board = new ArrayList<>();
for (int i=0; i<3; i++) {
board.add(new ArrayList<Character>());
}
Now you can start adding Characters to your lists:
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
board.get(i).add('A');
}
}
Hope this helps.
First you have to initialize the ArrayList in your first line correctly and than you have to initialize an new ArrayList in each run of your first loop:
ArrayList <ArrayList<Character>> board = new ArrayList<ArrayList<Character>>();
for (int i = 0; i < 3; i++){
ArrayList<Character> innerList = new ArrayList<Character>();
board.add(innerList);
for (int j = 0; j < 3; j++){
innerList.add('[');
}
}

Display elements without redundancy in an array

I made this code. I think it is wrong.
public void display() {
for (int i = 0; i < tabT.length; i++)
if (tabT[i] != null)
for (int j = 0; j <= i; j++)
if (tabT[i] != tabT[j])
System.out.println(tabT[i].getCar());
}
How do I display elements without redundancy in an array?
If you want to use only arrays, you can do something like this:
Make an temp (helper) array, which will include each element seen so far in tabT. Then, before printing the value, you check if it's not appearing in the helper array (tmp).
For example, if you have values in tabT, and you don't want to print each one more than once:
int[] tabT = {1,2,3,1,1,2,6,7,2,7,1};
int[] tmp = new int[tabT.length];
boolean flag;
for (int i = 0; i < tabT.length; i++) {
tmp[i] = tabT[i];
flag = true;
for (int j = 0; j < tmp.length; j++)
if (tabT[i] == tmp[j] && i!=j) {
flag = false;
}
if(flag)
System.out.println(tabT[i]);
}
Output: [1,2,3,6,7]
You can easily apply this idea to your program, and you'll have each element printed only once:
Cars[] tmp = new Cars[tabT.length]; //Assuming tabT is from type Cars[]
boolean flag = true;
for (int i = 0; i < tabT.length; i++) {
tmp[i] = tabT[i];
if (tabT[i] != null) {
for (int j = 0; j < tmp.length; j++)
if (tabT[i].getCar().equals(tabT[j].getCar()) && i!=j)
flag = false;
if(flag)
System.out.println(tabT[i].getCar());
}
}
This will print each car (or whatever you're printing) only once.
Objects compared via equals() For example
if (!tabT[i].equals(tabT[j]))
you are comparing the references values not the objects
for (int i=0; i< tabT.length; i++) {
boolean f = false;
for (int j=i+1; j <tabT.length; j++)
if (tabT[i].equals(tabT[j])) {
f=true;
break;
}
if (!f)
System.out.println(tabT[i].getCar());
}
this should give you all combinations non-repeating for i and j, so we don't compare them multiple times.
== and != test equality at the object level (i.e. if both instances are the same). What you need is to compare the value represented by each object (e.g. if two strings are equals), then you need to ask whether !tabT[i].equals(tabT[j]), and make the elements of tabT implement equals).
Or convert the array to a set, which removes duplicates.
T[] tabT = ...
Set<T> set = new LinkedHashSet<T>(Arrays.asList(tabT))
for (T t:set) System.out.println(t);
I used a LinkedHashSet because it preserves the order of the elements in the array. Note that you need to implement equals and hashcode.
Put tabT array in a Set. There will be no duplicate items.
Set tabTList = new HashMap(Listjava.util.Arrays.asList(tabT);
Why not trying something like this? (I'm supposing that you are working with String types)
HashSet<String> hashSet = new HashSet<String>();
for (int i = 0; i < tabT.length; i++) {
hashSet.add(tabT[i]);
}
You can't have duplicates into a set, so now you can iterate the set to get the uniques.
java.util.Iterator<String> iterator = hashSet.iterator();
while (iterator.hasNext()) {
System.out.println((String)iterator.next());
}
You could consider a HashMap if you do want to keep track of duplicate count. Iterate through array once to place objects into the HashMap with their respective counts. Then iterate through the array again checking against the HashMap. This would be O(n) time as opposed to potential O(n^2)

Array of LinkedList adding new nodes

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.)

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

Categories