-2

I have the following class for arraylist with int array.

public class MyClass extends ArrayList<MyClass> {

public int[] numAsc = {};
public int[] numDsc = {};

public MyClass(int[] numAsc , int[] numDsc){
    this.numAsc = numAsc ;
    this.numDsc = numDsc;

}
}

When I am trying add elements to arraylist, I am just getting empty arrays.

ArrayList<MyClass> numberSeries = new ArrayList<MyClass>();
int[] orders  = {1,2,3};
int[] request = {3,2,1};
numberSeries.add(new MyClass(orders,request));

Log.d(TAG, "numberSeries: " + numberSeries);

RESULT FROM LOGCAT: numberseries: [[]]

What am I missing here?

yivi
  • 42,438
  • 18
  • 116
  • 138
cantona_7
  • 1,127
  • 4
  • 21
  • 40

2 Answers2

3

I don't see why you extend ArrayList. I think you are overthinking it, if you just want to build a list of MyClass it does not need to extend ArrayList

  • Remove the extend,
  • make a sensible toString method on your MyClass object so you can see the values in your arrays
class MyClass {

    public int[] numAsc;
    public int[] numDsc;

    public MyClass(int[] numAsc , int[] numDsc){
        this.numAsc = numAsc ;
        this.numDsc = numDsc;
    }

    @Override
    public String toString() {
        return "numAsc: " + Arrays.toString(numAsc) + " | " +
                "numDsc: " +  Arrays.toString(numDsc);
    }
}

Then run your main, it outputs:

numberSeries = [numAsc: [1, 2, 3] | numDsc: [3, 2, 1]]

Krzysztof Cichocki
  • 6,294
  • 1
  • 16
  • 32
Bentaye
  • 9,403
  • 5
  • 32
  • 45
2

Please consider the following points:

  1. MyClass does not need to extend ArrayList.
  2. Use Generics to instantiate the concrete classes e.g. List<MyClass> numberSeries = new ArrayList<MyClass>();
  3. Override the toString() method in MyClass so that it becomes easier for you to print it.

Given below is the complete program incorporating the above points:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MyClass{

    public int[] numAsc = {};
    public int[] numDsc = {};

    public MyClass(int[] numAsc, int[] numDsc) {
        this.numAsc = numAsc;
        this.numDsc = numDsc;
    }
    public String toString() {
        return "numAsc: "+Arrays.toString(numAsc)+", numDsc: "+Arrays.toString(numDsc);
    }
}

public class TestMyClass{
    public static void main(String[] args) {
        List<MyClass> numberSeries = new ArrayList<MyClass>();
        int[] orders  = {1,2,3};
        int[] request = {3,2,1};    

        numberSeries.add(new MyClass(orders,request));

        System.out.println(numberSeries);
    }
}

Output:

[numAsc: [1, 2, 3], numDsc: [3, 2, 1]]
Krzysztof Cichocki
  • 6,294
  • 1
  • 16
  • 32
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110