-1

I'm wondering how would I make an arraylist be the name of a variable which is defined in the class somewhere else? like:

String list1 = "cheese";
ArrayList<String> list1 = new ArrayList<String>();

I tried that but it didn't work.

EDIT: I WANT TO NAME THE ARRAYLIST WHATEVER THE String list1 is.

user3717254
  • 19
  • 1
  • 2

4 Answers4

1

You can't do this, because variable list1 already has type String and you can't assign to this variable value of ArrayList type.

If you need new ArrayList with list1 variable there, you need to create new variable, for example ArrayList<String> list2 = new ArrayList<String>(); and add list1 to list2 like this list2.add(list1)

Aleksandr Podkutin
  • 2,532
  • 1
  • 20
  • 31
0

I think you want to set a variable name. I don´t know of any case where this would be possible, because you need a unique name (in special cases like creating variables among a method you can have several with the same name) for a variable to use it.

So the only way ist to use in a way @Alexander Podkutins suggestion:

 ArrayList<String> list1 = new ArrayList<String>();
Sebastian Walla
  • 1,104
  • 1
  • 9
  • 23
0

You cannot do this with fields since you cannot declare them twice. However, you can create a local vairable in a method with the same name.

Fields

This will NOT WORK EVER because you create a variable called list1 and you cannot create a second variable with the same name. No matter what the type is!

public class SomeClass {
    String list1;
    ArrayList<String> list1 = new ArrayList<String>();
}

Local variables

However, you can create a local variable with the same name inside a method. This variable will overlay the original (the original will not be "deleted" or so, you can still access it with this.list1). Note that this is considered a bad pratice, since it makes you code very hard to read.

public class SomeClass {
    String list1;
    public void myMethod(){
        ArrayList<String> list1 = new ArrayList<String>();
        // to get the original string do:
        this.list1;
    }
}
Am_I_Helpful
  • 18,735
  • 7
  • 49
  • 73
Thomas Uhrig
  • 30,811
  • 12
  • 60
  • 80
0

Java is statically typed, meaning that there are a specific set of data types an once a variable is initialized the data type can never be changed. On a side note, it is hard to understand what you want to accomplish?

martin.code
  • 1,291
  • 9
  • 12