Jtables (Array constant initilaizers) java - java

Ok basically what I am doing is i have a jtable in which users can enter their information into the table, I then want to be able to save it into a text file. The problem I am running into however is along the lines of this.
private static String dataValues[][];
I want to be able to declare dataValues like this so I can accesses it in every method so I can add rows to my jtable like this:
dataValues = {{number, owner, txtDate"}};
tableModel.addRow(dataValues);
however I get an error on the dataValues saying that "Array constants can only be used in initializers." And i dont really understand what that means.
if I declare the variable like this in the actual method it works.
String[][] dataValues = {{number, owner, txtDate}};
But I need to be able to access it anywhere in the program so declaring it like that will not help me.
Thanks for the help in advance.

The JTable represents the data internally with a TableModel. What the JTable does in the constructor is convert the initial array into the TableModel. What you need to do is think in terms of TableModels as described in the following link: http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#data

You can always initialize array variables like so:
static String[] row;
and later:
row = new String[]{"foo", "bar", "baz"};

"Array constants can only be used in initializers." - is a java syntax error.
You can not use statement like :
int[] a = new int [3];
a = {1,2,3};
I think with "a = {...}" it is not clear to the "javac" compiler what the type of "a" is.
Especially when dealing with array of objects such as Strings.
So use of constants allowed are
int[] a = {1,2,3};
Or possibly
a = new int [] {1,2,3};
Above should the only way if you really want to do what you are trying to do.
Essentially, this is how your code would look like:
dataValues = new String[][] {{"number", "owner", "txtDate"}};
That for the Java syntax error part. For JTable stuff, please follow #Stphane G's answer

Have a look at this answer i had given for a question on using a generic table model. You will find using a class with the fields representing the columns of the table a very easy implementation to work with
Is there a generic TableModel we can use in JTables?

Related

How can I use an array name as an array after taking it from another array in Java?

My Code:
String[] rice = {"white", "brown", "none", "all"};
String[] ingredients = {"rice", "meat", "beans", "salsa",
"veggies","cheese","guac", "queso", "sour cream"};
ArrayList<String> ingredientList1 = new ArrayList<String>();
for (int i = 0; i < randomNumbers.size(); i++){
ingredientList1.add(ingredients[i]);
}
My Question:
I have an array of array names. When I access the names, I cannot use them. Why not? It appears to be a data type conflict -- how can I resolve it? I do not know how to convert or cast a string into a String[] array.
ingredientList1.get(i).get(0) will index the ArrayList, "rice."
How do I use "rice" as an array name? rice[0] does not work.
The "rice" in your ingredients array is just a String. It has no link to the array: String[] rice.
There are many other ways to achieve what you're suggesting, but what you're specifically trying to do is reflection. In order to access the arrays by name, you would need to declare them as fields in a class, and then access the class fields using reflection. E.g. MyArrays.class.getDeclaredField....
Best to read a quick tutorial on reflection: https://www.oracle.com/technical-resources/articles/java/javareflection.html
It will certainly be useful to learn about reflection, but a much better way to achieve this would be to structure your data differently, for example you could use a simple Map to store your data. The key of the map would be the ingredient, and the value would be the types of those ingredients.

creating lists in java

So I am pretty new to java, and am trying to create a list in java with this:
private creatureKind[] field = new creatureKind[7];
creatureKind being another class I created within the same package. Is this the right syntax? I am trying to call functions such as set(), which
I found on this link: https://docs.oracle.com/javase/8/docs/api/java/util/List.html#set-int-E-, but I am getting an error message that abridged is saying that field is an array type. Not a frequent poster of this site so sorry if I messed stuff up in advance.
What you defined is a static array with a 7 element.
If you want to define a list, or better, an ArrayList you should it as follows:
List<creatureKind> list = new ArrayList<>();
Note that this is an unbound list, you should add values, before setting values. In general, I would suggest reading the documentations: https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
If I understood your question correctly, you might need to do the following:
List<creatureKind> myList = new ArrayList<>();

How to combine array with arraylist in Java?

I need a 5-dimensional data structure in Java with "double" as type for all the cells. For 3 of dimensions I know the size, so it fits to array category. But for 2 of dimensions I don't know the size beforehand; looks like ArrayList.
I have been able to manage the combination for 3 dimensions in the past:
ArrayList(Double)[][] prXifY = (ArrayList(Double)[][]) new ArrayList[m][n];
But despite long hours working on it (and through search in the net), I wasn't able to scale it. I need something like this:
ArrayList(ArrayList(Double))[][][] prXiXjY = (ArrayList(ArrayList(Double))[][][]) new ArrayList(ArrayList<Double))[m][m][n];
When I tried the above code, it says:
"Cannot create a generic array of ArrayList(ArrayList(Double))"
I will appreciate quick and complete answers.
By the way, this is my very first post ever. I tried my best to do a good job on searching beforehand and explaining the problem clearly. Comments on these matters are appreciated as well. :)
An ArrayList is an object, and instantiated differently than an array is. In general, to say that you want an ArrayList that holds doubles, you might use something like:
ArrayList<Double> list = new ArrayList<Double>();
to specify that you have an ArrayList which holsts ArrayLists which hold doubles...
ArrayList<ArrayList<Double>> list = new ArrayList<ArrayList<Double>>();
You see where this is going, I hope.
This just creates the top-level list - it doesn't create any of the cells themselves. For that, you'll need additional new statements. This is going to get messy fast, and you may want to stop and consider if there is a better way to store the data than in a 5-dimension array.
I think what you want would look something like this
List<List<List<List<List<Double>>>>> myList= new ArrayList<List<List<List<List<Double>>>>> ();
as you can tell this looks insane and will be very hard to maintain. You should probably look at alternative methods of doing this.
Multi dimensional arrays can be created like so:
ArrayList<Double> oneDimensionalArrayList = new ArrayList<>();
ArrayList<ArrayList<Double>> twoDimensionalArrayList = new ArrayList<>();
ArrayList<ArrayList<ArrayList<Double>>> threeDimensionalArrayList = new ArrayList<>();
ArrayList<ArrayList<ArrayList<ArrayList<Double>>>> fourDimensionalArrayList = new ArrayList<>();
ArrayList<ArrayList<ArrayList<ArrayList<ArrayList<Double>>>>> fiveDimensionalArrayList = new ArrayList<>();
But I would definitely recommend considering whether a 5 dimensional array is what you require for the problem at hand; it smells like something is wrong

Error on Shuffling xml layouts using ArrayList

I'm new with ArrayList. I don't get it.
If I use int[] as the ArrayList item there is an error saying:
The method put(int) is undefined for the type ArrayList<int[]>.
If I use int the error says:
Syntax error on token "int", Dimensions expected after this token
I tried to use add() still the same...
You can't use primitive types int etc, as the "type" of an ArrayList. You must use the wrapper class Integer instead. Also, I stand to be corrected, but I don't think you can have an ArrayList of an array type for similar reasons. Perhaps ArrayList<ArrayList<Integer>> would work, as slightly ugly as that is?
EDIT: And while my Android experience is somewhat minimal and rusty, ρяσѕρєя K's comment about R.layout.foo always returning an int is certainly right.
Use something like this :
ArrayList<Integer []> mArrayList = new ArrayList<Integer[]>();
Integer [] layouts = {R.layout.layout1,R.layout.layout12,...};
mArrayList.add(layouts);
ArrayList<Integer> mArrayList = new ArrayList<Integer>();
mArrayList.add(R.layout.layout1);
mArrayList.add(R.layout.layout2);
...

Any way to insert an anonymous array into a collection?

I've found plenty of entries here that say
someFunc(new int[]{1,2,3});
works for calling methods and being used in a for/each loop.
//======
How about for assignment into a collection?
I've tried this:
ArrayList<int[]> data = new ArrayList<int[]>();
data.add(new int[]{21, 19629});
and I get "identifier expected" and "illegal start of type".
Is there any thing I can do to make this work?
You've made a list of arrays. Was that really what you intended, or did you mean to ask about something like
ArrayList<Integer> data = new ArrayList<Integer>();
data.add(new int[]{1,2,3});
?
In any case, familiarize yourself with the Arrays and Collections classes--they contain a lot of utilities that come in handy in cases like this.
Easiest way to make a list from an array:
List<String> myList = Arrays.asList("Hello", "There", "Foo", "Bar);
Note the list is fixed size and backed by the input array so changes to the list actually write to the array. Adding or removing elements will likely result in an UnsupportedOperationException. If you intend to mess around with the array such as adding or removing elements you may need to copy the elements into another list
Check out guava, especially the google collections part.
Several of the collection classes define a static method of(...) which will the add all objects given to that collection.
Combined with static imports this allows very concise colleciton intializations on-the-fly.
e.g.
import static com.google.common.collect.ImmutableList.of;
...
someFunc(of("abc","def","ghi"));
will call someFunc with a list of strings.
In fact, this code works if you want to make a list of table of integers.
public static void main(String[] args) {
List<int[]> data = new ArrayList<int[]>();
data.add(new int[]{21, 19629})
for(int[] tab : data){//I loop each tab (only one here)
for(int i: tab){//I loop each values
System.out.println(i);
}
}
}
print
21
19629
This may be a limitation of the language syntax, or a bug in the spec that the identifier production is being found before the expression production in the parsing of the method call syntax. Don't mix anonymous array declaration inside the method call.
data.add(new int[]{21, 19629});
and I get "identifier expected" and
"illegal start of type".
The "identifier expected" in data.add(...) is probably caused by the compiler expecting an identifier and finding an expression that resolves to an anonymous instance. There are several places where that very syntax is acceptable, I'm not sure why data.add() needs an identifier.
The "illegal start of type" may be that the compiler thinks the expression is an anonymous type declaration but the syntax doesn't allow for that in a method call.
Try creating it using a variable, then pass the variable as the method arg.
int[] nums = new int[] {0,1,2};
data.add(nums);
In looking for more specifics of the ArrayList.add() grammar, I found this answer on a similar problem someone had learning ArrayList. JavaGlossary has a good set of Compile-time errors.

Categories