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...
...
}
Related
I want to have a array of integers where the length is variable. The obvious choice is to use ArrayList but can I do this for primitive types such as
ArrayList<int> myArray=new ArrayList<int>();
I dont want to use
ArrayList<Integer>
because the Integer class is clumsy in terms of coding.
EDIT: From the answers below I think the solution is to write my own Integer class.
To answer the question below about "clumsy" let me give a specific, and I would of thought common use for integers namely using the last member of the array in any place you would want the integer. If I just call the array "name" then to get the actual integer that can be operated on I need
name.get(name.size()-1).intValue();
To me this seems like an awfully unwieldy expression for a simple integer - particularly if it appears in an expression twice. It also seems that (most of the) methods available for the Integer class are absolutely redundant. Take two examples
static int compare(int a, int b)
Quite unbelievably, according to the documentation, this method returns a-b!!
static Integer valueOf(int a)
returns an Integer instance of the integer a. Can someone give me a single example where
new Integer(a)
does not achieve exactly the same result?
Method 1: (not recommended)
You can do something like this, but this doubles the code and is not efficient:
int[] a;
//get size (from command line maybe ow whatever method you want)
You can set size 0 initially, and for ex. you are transferring values from arraylist so you will have to write:
while(itr.hasNext()){
size++;} //itr is an object of Iterator
int i=0;
a=new int[size];
// then loop again to store values
while(itr.hasNext()){
a[i]=itr.next();
i++;}
Method 2:
Or you may use ArrayList without making it clumsy as follows:
ArrayList al=new ArrayList();
then you may declare Integer objects as volatile and perform operations on them just as you do with the primitive types.
Method 3: (not recommended)
Or simply write:
ArrayList al=new ArrayList();//ignore the warning about <E>
int x=2;
al.add(2);
Method 4: (recommended)
If I were you I would use ArrayList<Integer>.
UPDATE: Another thing that might work is that you may initially create an ArrayList<Integer> and store values there and later convert it to int[]
This SO answer tells about the conversion. Quoted the code form there:
public static int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
for (int i=0; i < ret.length; i++)
{
ret[i] = integers.get(i).intValue();
}
return ret;
}
Hope this helps.
No it's not possible to use primitive types as generic type.
Well I would recommend you do use ArrayList and avoid primitive types in this case.
You can't change the size of an array once created. You have to allocate it bigger than you think you'll ever need
or
Accept the overhead of having to reallocate it to a new larger array and copy the data from the old to the new:
System.arraycopy(oldItems, 0, newItems, 0, 10);
But Much simpler to go with ArrayList.
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
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.
Is using an arraylist of Tuple(double,int,int) slower than three separate arraylists? I want to avoid creating lots of Tuple objects, but does method 2 create objects by autoboxing?
//Method 1
Arraylist<Tuple> arr=new Arraylist<Tuple>();
Tuple t=new Tuple(double, int, int);
class Tuple{
private double value;
private int a;
private int b;
}
//Method 2
Arraylist<Double> arr=new Arraylist<Double>();
Arraylist<Integer> arr=new Arraylist<Integer>();
Arraylist<Integer> arr=new Arraylist<Integer>();
Your question is missing context. This problem has been asked many times, and there is no single best solution.
In my opinion, the best way to model the data is to have a logical type that represents your data. (You are currently using a tuple, but it would be better to have a specific type with methods.)
So, I would do the following:
List<NumberContainer> list = new ArrayList<NumberContainer>();
As far as speed goes in particular - It depends on how you are going to use the data. If you are looking for fast access times, it may be best to use a map and key each item on some value.
Unless you've written a custom Tuple class which maintain an unboxed double and two int values, they'll be boxed anyway... so basically you'll end up with the extra Tuple object per item, although just one underlying array and ArrayList instead of 3.
If the triple of values represents a meaningful composite value though, I'd be very tempted to write a small class to encapsulate the three of them with meaningful names for each property. That way you're likely to end up with more readable code and efficient code (as there won't be any boxing).
Most likely using an array of objects (or in your case, tuples) which would save you a line of code, and put everything in one place (the tuple.)
Here's the sample code for what I would do.
//Class
class container() {
int value1, value2;
double value3;
//Constructor
container(int value1, int value2, double value3) {
this.value1 = value1;
this.value2 = value2;
this.value3 = value3;
}
}
//Implementation
ArrayList<container> arr=new ArrayList<container>();
If Tople is a class with 3 ivars, in that case that would be the way to go.
Aditionaly arralist only take objects so it will autobox all the primitives, but if you are using a class it will definitly not autobox the ivars in the class.
To answer your direct question, method2 does create objects by autoboxing assuming that the values you're putting in are primitives (double, int, etc.). Of course, if you use a Tuple class, you're also creating objects, but you will be creating 1/3 the number of objects, assuming the Tuple class maintains two ints and a double.