-3

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
  • 1
  • 16
  • 86
  • 115
cantona_7
  • 937
  • 4
  • 18
  • 36

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
  • 5,856
  • 1
  • 15
  • 31
Bentaye
  • 8,857
  • 4
  • 30
  • 41
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
  • 5,856
  • 1
  • 15
  • 31
Arvind Kumar Avinash
  • 62,771
  • 5
  • 54
  • 92