I have following lines of code:
private ArrayList<wordClass>[] words;
and
public class wordClass {
public String wordValue = null;
public int val = 0;
public boolean used = false;
}
Is there anyway I can access wordValue, val, and used via words? Like words[5].val? I know I can do that if they are just in an array of wordClass, but I want a dynamic array to make it easier to add and subtract from the array.
And yes, I know the values should be private. Just don't want to write getters and setters yet.
Thanks.
Do you really want an Array of an ArrayList?
It doesn't seem correct.
In Arrays, you use [] to access (words[0]).
In ArrayLists, you should use words.get(0).
The way you have coded, you should use: words[0].get(0).val to get the very first value.
But I recommend you to review your words definition.
ArrayList Documentation: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
Regards,
Bruno
Your code is a bit off for a dynamic array (Java has immutable arrays), so you need an ArrayList. Also, Java uses Capital Letters for class names (please follow the convention) -
// like this, changing wordClass to WordClass. Also, using the diamond operator
private ArrayList<WordClass> words = new ArrayList<>();
To access your WordClass fields you can use something like -
for (WordClass wc : words) {
if (wc.used) {
System.out.println(wc.wordValue + " = " + wc.val);
}
}
Note, you still need to create WordClass instances and place them into the words List.
Write wrapper classes for each value. e.g. What you call "getters".
Then call:
words[1].getWordValue() ==> None
Voila
Related
I want a 2D Matrix with one line of strings and the other line with int's.
Is that possible?
Or do I have to save the int's as strings and later convert them to int's again?
Rather use an object.
class MyEntry {
String foo;
int number;
}
MyEntry[] array = new MyEntry[10];
But if you must, you can use two types - only through an Object supertype.
Object[][] arr = new Object[2][10];
arr[0][0] = "Foo";
arr[1][0] = new Integer(50);
No it is not possible . There can be only a single datatype for an array object. You can make a class having both the int and String as property and use it. Never use an Object[][] even if there is a temptation to do so, it is an evil workaround and hacks fail more than they succeeded . If Object was a sound technique then they wouldn't have introduced Generics for Collection !
You can create Objects 2D array and place there Strings and Integers, but I am not sure if it is good idea to have mixed types in arrays. You should probably describe your problem more so we could figure out better way.
Yes it is. If you declare as a Matrix of object then you can store string and Integer (not int), the difficulty will be after to retrieve them correctly :)
You can create an array of the type Object and store any non-primitive Object in there.
When you retrieve them, you'll need to make sure you check their class though.
if(objArray[0] instanceof String) {
// do string stuff
} else if(objArray[0] instanceof Integer) {
// do integer stuff
}
etc.
I think you're better off creating a new class that can store objects of the types that you want and just retrieve them using getters and setters. It's a lot safer and more stable.
You could do it if you do a 2D array of Object as in Object[][] myArray = new Object[x][y] where x and y are numbers.
All you would have to do is cast the Objects to their expected types before using them. Like (String) myArray[0][3] for example.
YOu should only do it this way if you know for certain what type the Object in a particular location will be.
However, it's generally not a good idea to do things this way. A better solution would be to define your own data structure class that has a String array and an int array as member variables. As in:
public class myData {
String[] theStringArray;
int[] theIntArray;
public myData(String[] sArraySize, int[] iArraySize) {
this.theStringArray = new String[sArraySize];
this.theIntArray = new int[iArraySize);
}
...
// Additional getters / setters etc...
...
}
I am trying to create an array of a class within a class so that I can have multiple sets of the inner class. However because I cannot create an empty an array in Java, I was wonder what's the best way to set this up. I know I can just define an array that is bigger than I would ever use but I feel that kind of sloppy programming.
Here's the important part of the 2 classes:
public class xmldata {
String Barcode;
String First;
String Last;
String Phone;
String Email;
String md5sum;
String zipfile;
picture_data[] pics;
...
public class picture_data {
static String filename;
static String directory;
As you can see, I to have an array of picture_data in xmldata. I have seen some stuff using lists but the examples are different and I am not sure I understand how to apply it in my case.
Here's the code I used to try and populate the arrays.
xmldata data = new xmldata();
ResultSet pictures=db.query("select * from pictures where barcode=?",barcode);
int i = -1;
while (pictures.next()) {
++i;
data.pics[i].setdirectory(pictures.getString("path"));
data.pics[i].setfilename(pictures.getString("filename"));
}
Any suggestions would be appreciated.
Modern idiomatic Java doesn't use raw Arrays or Vector either, it uses type safe List implementations.
Also picture_data and xmldata are not idiomatic naming convention for classes in Java, it should be PictureData and XMLData. I would challenge the semantics of a class called PictureData or XMLData as well.
A correct solution would be something like
List<PictureData> list = new ArrayList<PictureData>();
Understanding how to work with the Collections framework in Java is a fundamental requirement to be productive. Type safe Lists are a core component to writing real Java code.
If your array's size is going to be dynamic, then use lists inside and an ArrayList precisely. This way, you don't have to take care about size because it's treated internally.
Create an object of picture_data and add it into a ArrayList of picture_data
Then convert that arraylist into an array
Convert ArrayList<String> to String[] array
http://www.java-tips.org/java-se-tips/java.lang/how-to-convert-an-arraylist-into-an-array.html
Best option would be to use lazy initialized ArrayList
public class Xmldata {
List<picture_data> pics;
public void addPics(picture_data data) {
if(pics == null) pics = new ArrayList<picture_data>();
pics.add(data);
}
}
Here the pics list will only be created if the picture_data type objects are added to the Xmldata class
I have an ArrayList of my own class Case. The class case provides the method getCaseNumber() I want to add all of the cases casenumber to a String[] caseNumber. I've tried this
public String[] getCaseNumberToTempList(ArrayList<Case> caseList) {
String[] objectCaseNumber = null;
for(int i = 0; i < caseList.size(); i++) {
objectCaseNumber[i] = caseList.get(i).getCaseNumber();
}
return objectCaseNumber;
}
But my compiler complaints about that the objectCaseNumber is null at the point insid the for-loop. How can I manage to complete this?
Well, you need to create an array to start with, and initialize the variable with a reference to the array. (See the Java tutorial for arrays for more information.) For example:
String[] objectCaseNumber = new String[caseList.size()];
Alternatively, build a List<String> (e.g. using ArrayList) instead. That's more flexible - in this case it's simple as you know the size up front, but in other cases being able to just add to a list makes life a lot simpler.
In idiomatic Java, you wouldn't use ArrayList as a parameter type. Use List.
Slightly more overhead, but simpler and more readable code is to accumulate in another List and then convert into an arrray:
public String[] getCaseNumberToTempList(List<Case> caseList) {
final List<String> r = new ArrayList<String>();
for (Case c : caseList) r.add(c.getCaseNumber());
return r.toArray(new Case[0]);
}
In your code it does make sense to insist on ArrayList due to performance implications of random access via get, but if you use this kind of code (and I suggest making a habit of it), then you can work with any List with the same results.
Well, as I think you may have misunderstood Arrays as a primitive type. Arrays in java are objects and they need to be initialized before you access it.
I am a beginner with java, and I was wondering is if is possible to name and create an array from the value of a string.
Here is what I have:
public static void array(){
createArray(array1, 100, 100);
}
public static void createArray(String name, int r, int c) {
int[][] name = new int[r][c];
}
I hope that explains itself. Thanks
EDIT: The code above does not work. I just want to know if it is possible to do what is above
EDIT2: As a beginner with java, I am just watching tutorials, and creating programs with what I learned to make sure I understand what is being taught. I first created a program which creates s multidimensional arrays. It then calls a method which assigned values to the array, (row+1)*(column+1). This makes a table much like a multiplication table. Then it displays the table to the screen.
After I created that program, I wanted to be able to create arrays much like I assigned the values to it. So i asked this question...
Here is my code:
public static void array(){
int[][] array1 = new int[100][100];
int[][] array2 = new int[20][20];
setArrayValue(array1);
setArrayValue(array2);
drawArray(array1);
System.out.println();
drawArray(array2);
}
public static void setArrayValue(int x[][]){
for(int row = 0; row<x.length; row++){
for(int column=0; column<x[row].length; column++){
x[row][column]= (column+1)*(row+1);
}
}
}
public static void drawArray(int x[][]){
for(int row=0; row<x.length; row++) {
for(int column=0; column<x[row].length;column++){
System.out.print(x[row][column] + "\t");
}
System.out.println();
}
}
Your concept doesn't make sense.
You might want to use a Map<String, int[][]>, which will map names to arrays.
What you are trying to do is not possible in Java. In the createArray method, name is of type String and cannot be redeclared as an int array.
Perhaps you are interested in a Map that uses String objects as keys? The values could be int arrays (or any other object).
No, you can't do that.
Variable names are not variable in Java.
Furthermore, local variables even lose their names when the code is compiled. Variable names are just a help for the programmer to distinguish between variables.
Nop can't be done. Variable names need to be known before hand.
No, it is not possible. You might be able to accomplish your task with a TreeMap or another Map implementation instead.
Instead of saying
name = something;
You would say
map.put(name, something);
Instead of
name[0] + 7
You'd say
map.get(name)[0] + 7
As stated by others - this cannot be done. That is because Java compiler needs to know exact name of a variable at the compile time. This is mandatory, since otherwise Java compiler wouldn't know which variable you are addressing, so it couldn't perform, for instance, type-safety checks.
However, if you just wish to stamp your variable with some unique ID, I guess the solution is closest to what has been stated by SLaks. Simply use Map, and You should be good. Example below.
Map<String, int[][]> myMap = new HashMap<String, int[][]>();
myMap.put("someUniqueName", new int[][] {{0,0}, {1,1}});
and later on:
int[][] array = myMap.get("someUniqueName");
Hope that helps achieve what You want.
Strictly: almost ;-) You can add a dynamic field in a class, which could be an array, using AOP. But...
It's difficult.
This solution is too complicated in most cases. You could probably solve your real problem in a much easier way.
Some advice: start with the beginning... and try using List (interface) / ArrayList as much as possible unless you have some pretty good reason to use an array.
here i am trying to add elements to the array.
the elements i am trying to add are text fields, so im basically trying to store persons contact details within the array list?
any help would be greatful
public void addContact()
{
ArrayList<String> details = new ArrayList<String>();
{
details.get(txtname(0));
details.get(txtnum(1));
details.get(txtmob(2));
details.get(txtadd1(3));
}
}
It sounds like you haven't thought out the entire problem yet.
Adding elements to an ArrayList in Java is done like this:
public void addContact(){
ArrayList<String> foo = new ArrayList<String>();
foo.add("HELLO");
foo.add("WORLD");
}
yankee2905 explains it very well; that's what you need to get your code to work with an ArrayList.
As a side note, you're not dealing with an array, you're dealing with an ArrayList. For an array, you might have something like this:
String[] details = new String[4];
details[0] = "First";
details[1] = "Second";
details[2] = "Third";
details[3] = "Last";
It almost sounds like you're trying to use an ArrayList to store contact information for multiple people. If that is the case, you will probably want to do it a bit differently. You can create a Contact object that has members for each piece of information you want to store (e.g. firstname, lastname, phone, mobile, address1, address2, etc). Then you can just add Contact objects to your ArrayList like:
Contact contact1 = new Contact();
contact1.setFirstname("Bob");
myArrayList.add(contact1);
public void addContact()
{
ArrayList<String> details = new ArrayList<String>();
{
details.add(//Insert value from post here);
details.add(//Insert value from post here);
details.add(//Insert value from post here);
details.add(//Insert value from post here);
}
}
I've not used java in a while maybe someone will add to this.
You need set or add, not get. See the docs here.
And to get the text from the textfields, use getText.
So you'd have something like:
myArrayList.add(myTextField.getText());
You are trying to use inbuilt array initializer syntax. That does not work on container classes (unless its some new fangled way in c#) you need to use details.add() (or the appropriate member function).
The syntax you are trying to use is for the language supported hardwired array types. In C++ this would look like char x[6] = {'h','e','l','l','o'};. However a container is not an array its a container object. Container objects often mimic arrays by overloading operator[] however they use different data structures behind the scenes -- i.e., they do not use contiguous regions of memory.
p.s., If this was c#.NET -- which I initially assumed -- there is a new mechanism to map array initialization to container object creation. I'll leave it down there for anyone that is interested.
in C# 3.5 using array initializer syntax you can do the following :
public void addContact()
{
ArrayList<String> details = new ArrayList<String>()
{
details.get(txtname(0)),
details.get(txtnum(1)),
details.get(txtmob(2)),
details.get(txtadd1(3))
}
}
Gotta love Microsoft and C# :P
public void addContact()
{
ArrayList<String> details = new ArrayList<String>();
details.add(txtname.getText());
details.add(txtnum.getText());
details.add(txtmob.getText());
details.add(txtadd1.getText());
}
Sorry I don't have an IDE open, but I think this is closer to what you are after.
I think this is the best solution if you want to create an array with some elements:
String[] images = {"a.png","b.png","c.png"};
or
String[] images;
images = new String[]{"a.png","b.png","c.png"};