0

I'm new in java, what is the right way to add/pass a value into array string without specifying the array index.

I want to add a value into array like what in php array do.

static String[] var_productname = new String[20];

public void setProductName(String productName){
    var_productname[] = productName;

}
2
  • 1) I'm not sure Android is the good starting point for "new to Java". 2) static doesn't play well with setter methods 3) Why is a "productName" an array? Sounds like a singular object Commented Jan 24, 2017 at 1:29
  • Are you asking how to expand the array capacity, or how to keep an implicit index? Commented Jan 24, 2017 at 1:30

4 Answers 4

2

You can use an List implementation as ArrayList.

Based on your example:

static List<String> var_productname = new ArrayList<>();

public void setProductName(String productName){
    var_productname.add(productName);

}

The initial capacity is optional, but you can instantiate the array using new ArrayList<>(20), where 20 is the initial (not maximum) capacity.

Sign up to request clarification or add additional context in comments.

Comments

1

If you are just trying to avoid specifying the index when calling setProductName, here is a simple approach. (However, the method will internally use and update the index).

Note that this simple implementation will throw an exception if you attempt to append more than 20 strings. Also, I made setProductName a static method, which makes more sense since you made var_productname static.

static String[] var_productname = new String[20];
static int pnIndex = 0;

public static void setProductName(String productName) {
    var_productname[pnIndex++] = productName;
}

Comments

0

array can't append element direct,change array to other data structure

1 Comment

answers should be longer than one line;change answer to describe a more complete solution in context and maybe use full sentences and punctuation
0

In that case you would go for a concept called Collections

The problem with Arrays is that you cannot dynamically increase it's size at run time and you will only be able to add values as per the length specified.

As int[] nArray= new int[20]; will hold only 20 items you cannot further dynamically increase the size from 20 to 21 and add the element.

As suggested above you can go for any List implementation.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.