-2

I am trying to create an ArrayList from a given array. This is the array I have:

public class Warehouse
{

 private final static int MAX = 60;
 private Item [] stock;
 private int numItems;


  public Warehouse()
  {
   stock = new Item[MAX];
   numItems = loadData();
  }

Now where should I change the processing from an array to an arraylist? Is this supposed to be done in the constructor or somewhere else? Thanks.

c0der
  • 18,467
  • 6
  • 33
  • 65
Srk93
  • 37
  • 1
  • 6
  • Possible duplicate of [Create ArrayList from array](http://stackoverflow.com/questions/157944/create-arraylist-from-array) – Jérôme Mar 12 '17 at 03:08

2 Answers2

1

Why not use this?

List<Item> stockList = Arrays.asList(stock);
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Okay but do I have to put this in a separate method? I assume I leave the constructor and instance variables as they are and put this in another method? – Srk93 Mar 12 '17 at 02:39
  • All you wanted was an arraylist. That is what this does. Where you put it shouldn't matter – OneCricketeer Mar 12 '17 at 02:40
  • If all you want is a `new ArrayList`, then do that instead. – OneCricketeer Mar 12 '17 at 02:41
  • 2
    A small correction: this doesn't produce an `ArrayList`. Unlike an `ArrayList`, [the result of `Arrays.asList` is fixed-sized and can't be expanded](https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#asList-T...-). This can alternatively be verified by trying to assign it to an `ArrayList` instead of an `List`, which will fail. A way to create an `ArrayList` is with `List stockList = new ArrayList(Arrays.asList(stock));` – Chai T. Rex Mar 12 '17 at 03:05
  • @ChaiT.Rex The question didn't clearly specify that the list needed changed. – OneCricketeer Mar 12 '17 at 03:06
0

Just keep a separate class for the array and within the class that you want to get that specific array you can create an ArrayList Object.

public class ArrayaData {

public int Id;}

And the within the next class,

public class ClassYouWant {

  ArrayList<ArrayaData> arrayList ;

}

and when ever you want to add a value to that array just create a new instance and then save it.

arrayList = new ArrayList<ArrayaData>();
arrayList.Id = "Value you want.."
arrayList = new ArrayList<ArrayaData>();
arrayList.Id = "Value 2 you want.."

Or you can simply set it in a Loop as well,

int arraySize = 5; //Size of the array you want

    for (int i = 0; i < arraySize; i++) {

        arrayList = new ArrayList<ArrayData>();
        arrayList.Id = "Value you want";

    }

And to get the vlaues you can use a Loop also,

int arraySize = arrayList.size(); //Size of the created arrayList
int value;
    for (int i = 0; i < arraySize; i++) {
        value = arrayList.get(i);
       Toast.makeText(this, "Value " + i + ":" + value, Toast.LENGTH_SHORT).show();

    }

Hope this helps..

c0der
  • 18,467
  • 6
  • 33
  • 65