i have two array like this
String[][] name=new String[4][10];
boolean[] accun=new boolean[10];
name[0][0]="ali";
name[0][1]="max";
name[0][2]="ahmad";
etc.....
name[1][0]="9999";
name[1][1]="9999";
name[1][2]="9999";
etc...
and name[2][..] ,name[3][..] like that.
now how can i merge this two array together?like this.
name [5][0]=true;
name [0][0]="alex";
Thanks for your any Help.
The type of an array is the same for all elements of an array. The only way this would work for you is to use Object[][] because Object is a supertype of both String and Boolean. However, what you should probably be doing is creating a class which has members which are currently being represented by the different indices of your array. For example:
class Foo {
String name;
int count;
boolean isFoo;
}
Foo[] foos = new Foo[10];
foo[0] = new Foo();
foo[0].name = "aaaa";
foo[0].count = 9999;
foo[0].isFoo = true;
You should then also look into constructors and accessor methods to make the code more idiomatic Java.
Your question is bit ambiguous.My assumption is you are trying to ask how to different type of objects in array. Here you should go
Object[][] name = new Object[4][10];
Now you can store both int and string objects under name array.
Related
Is there a way to define a default value for an object in array to be initialized with?
In the same way that primitive types are initialized when declaring an array of them:
int[] myIntArray = new int[5]; // we now have an array of 5 zeroes
char[] myCharArray = new char[2]; // an array in which all members are "\u0000"
etc.
I'd like to declare an array of objects of a type that I've defined, and have them automatically initialize in a similar fashion.
I suppose this would mean I'd like to run new myObject() for each index in the array (with the default constructor).
I haven't been able to find anything relevant online, the closest I got was to use Arrays.fill(myArray, new MyObject()) after initializing the array (which actually just creates one object and fills the array with pointers to it), or just using a loop to go over the array and initialize each cell.
thank you!
EDIT: I realized this is relevant not just to arrays, but for declaring objects in general and having them default to a value / initialize automatically.
The Java 8 way:
MyObject[] arr = Stream.generate(() -> new MyObject())
.limit(5)
.toArray(MyObject[]::new);
This will create an infinite Stream of objects produced by the supplier () -> new MyObject(), limit the stream to the total desired length, and collect it into an array.
If you wanted to set some properties on the object or something, you could have a more involved supplier:
() -> {
MyObject result = new MyObject();
result.setName("foo");
return result;
}
Do this so you can initialize the array when declaring it:
int[] myIntArray = {0, 0, 0,0,0};
char[] myCharArray = { 'x', 'p' };
you could of course do:
int[] myIntArray = new int[5];
and the in a for loop set all indexes to the initial value... but this can take a while if the array is bigger...
Edit:
for custom objects is the same just use an anonymous constructor in the init
Example:
public class SOFPointClass {
private int x;
private int y;
public SOFPointClass(int x, int y) {
this.x = x;
this.y = y;
}
// test
public static void main(String[] args) {
SOFPointClass[] pointsArray = { new SOFPointClass(0,0) , new SOFPointClass(1,1)};
}
}
I don't see a way that Java provides to do this.
My suggestion would be define a function to do it.
Object[] initialize(Class aClass, int number) throws IllegalAccessException, InstantiationException {
Object[] result = new Object[number];
for (int i = 0; i < number; ++i) {
result[i] = aClass.newInstance();
}
}
Then call it as Object[] arr = initialize(YourClass.class, 10)
In Java, the array is initialized with the default value of the type. For example, int default is 0. The default value for cells of an array of objects is null as the array cells only hold references to the memory slot contains the object itself. The default reference points to null. In order to fill it with another default value, you have to call Arrays.fill() as you mentioned.
Object[] arr=new Object[2];
Arrays.fill(arr, new Object());
As far as I know there is no way of doing what you want with just plain java (that is to say there may be an external library I don't know about).
I would take the hit and loop over the array. Something like this should work:
myObject[] array = new myObject[5];
for (int i = 0; i < array.length; i++) {
array[i] = new myObject();
}
You could also shorten this using lambdas, like Cardano mentioned in his answer.
I am creating a list data structure and am having trouble with the generics syntax for actually using it. All I am trying to do is create an instance of ArrayLinearList<String> and of size 2 and put some strings in it. I have been trying to figure out why setting the first slot to "one" is not correct. This is the error and my code snippet.
myList[0] = "one";
The error message is: error: incompatible types: String cannot be converted to ArrayLinearList<String>
public class ArrayLinearList<E> implements LinearListADT<E> {
private Object[] array;
int currentSize = 0;
//Constructor (no arguments)
public ArrayLinearList() {
currentSize = 2;
// array = (ArrayLinearList[]) new Object[2]; //Start with a container of size 2
array = new Object[2];
}
public static void main(String[] var0) {
ArrayLinearList<String>[] myList;
myList = new ArrayLinearList[2];
myList[0] = "one";
}
}
I am having quite a bit of trouble with the syntax with using generics in java. In my mind I have an array of size 2 where I am going to be placing strings. I will add more methods later but I want to understand why my current syntax is incorrect for placing this string in the array.
Here:
ArrayLinearList<String>[] myList;
you define an array that holds ArrayLinearList<String> elements, not Strings, this is why you get the error message.
Your code here
ArrayLinearList<String>[] myList;
myList = new ArrayLinearList[2];//you have defining array myList of type ArrayLinearList
myList[0] = "one";//you are trying to store String to array which can hold ArrayLinearList
Here ArrayLinearList<String> means that your list will hold values of type String (provided we define it correctly in the code). But ArrayLinearList<String>[] will hold only reference of type ArrayLinearList and not String itself.
You need to use
myList.array[0] = "one";
Because myList is not an array. It's an object which you use to store an array within.
public class Sonnet29 implements Poem {
private String[] poem;
public Sonnet29() {
poem = { "foo", "bar" , "baz"};
}
#Override
public void recite() {
//...
}
}
Line poem = { "foo", "bar" , "baz"}; is giving compilation error.
Any specific reason why this is not allowed?
How do I initialize a String array with array constants?
EDIT: Thank you folks for your answers. Now I'm clear what is allowed and what is NOT.
But can I ask you why this is NOT allowed?
String[] pets;
pets = {"cat", "dog"};
After googling a bit, I found this link, where in, it is told that coding like this leaves the compiler in ambiguity - whether the pets should be array of Strings or array of Objects. However from the declaration, it can very well figure out that it is a String array, right???
This will do what you're looking for:
public Sonnet29() {
poem = new String[] { "foo", "bar", "baz" };
}
Initialization lists are only allowed when creating a new instance of the array.
From the Java language specification:
An array initializer may be specified in a declaration, or as part of an array creation expression (ยง15.10), creating an array and providing some initial values
In short, this is legal code:
private int[] values1 = new int[]{1,2,3,4};
private int[] values2 = {1,2,3,4}; // short form is allowed only (!) here
private String[][] map1 = new String[][]{{"1","one"},{"2","two"}};
private String[][] map2 = {{"1","one"},{"2","two"}}; // short form
List<String> list = Arrays.asList(new String[]{"cat","dog","mouse"});
and this is illegal:
private int[] values = new int[4];
values = {1,2,3,4}; // not an array initializer -> compile error
List<String> list = Arrays.asList({"cat","dog","mouse"}); // 'short' form not allowed
{"cat", "dog"}
Is not an array, it is an array initializer.
new String[]{"cat", "dog"}
This can be seen as an array 'constructor' with two arguments. The short form is just there to reduce RSI.
They could have given real meaning to {"cat", "dog"}, so you could say things like
{"cat", "dog"}.length
But why should they make the compiler even harder to write, without adding anything useful? (ZoogieZork answer can be used easily)
I need this code, but i get this error:
Ljava.lang.Object; cannot be cast to java.lang.String
public Object[] getAllKeys (){
return keys.toArray(new Object[keys.size()]);
}
public String[] getNames (){
return ((String[])super.getAllKeys()); <- Error here. Can't cast, why?
}
The type of the array is Object[] so it cannot know that it contains only Strings. It is quite possible to add a non-String object to that array. As a result the cast is not allowed.
You can return Object[] and then cast each of the objects within that array to string. i.e. (String)arr[0] or you can create a new String[] array and copy all the elements over before returning it.
toArray() returns an array of Objects. If you want to create an array of Strings out of it, you will have to do it yourself. For example,
Object [] objects = super.getAllKeys();
int size = objects.size();
String [] strings = new String[size];
for (int i = 0; i < size; i++)
strings[i] = objects[i].toString();
or something similar... Hope this is useful.
Every String is an Object. Every Object is NOT a String.
You cannot do the cast, because even though Object is a base class of String, their array classes Object[] and String[] classes are unrelated.
You can fix this problem by introducing an additional method that allows taking a typed array:
public Object[] getAllKeys (){
return getAllKeys(new Object[keys.size()]);
}
// Depending on your design, you may want to make this method protected
public <T> T[] getAllKeys(T[] array){
return keys.toArray(array);
}
...
public String[] getNames (){
return super.getAllKeys(new String[keys.size()]);
}
This code takes advantage of the other overload of toArray, which accepts a typed array as an argument.
This cannot be done implicitly since the runtime cannot know that the elements in Object[] are all String types.
If you don't want to code a loop yourself, then one way to coerce is to use
String[] myStringArray = Arrays.asList(keys).toArray(new String[keys.length]);
I think that this will happen without any string copies being taken: asList() binds to the existing array data and toArray uses generics which are removed at runtime anyway due to type erasure. So this will be faster than using toString() etc. Don't forget to deal with any exceptions though.
Try the following snippet
Object[] obj = {"Red","Green","Yellow"};
String[] strArray = (String[]) obj; // Casting from Object[] to String[]
hi i am new to java.After so research about what i am facing, i try post to ask some question.
recently i am doing a text analyse software.
and i try to get done with a 1*3 dimensional array.
something like
[0]
[][][]
[1]
[][][]
[2]
[][][]
[3]
[][][]
the three column in the second dimension of each is use for saving the details of the first dimension.
but the second dimension array size is yet unknown which mean that, idont know how many i will find from the text that i am gonna search.it will increase once the target found.
is this the stupid way for doing this.
i know java can declare array like int [][] abc = new [5][].
but it just can declare only for one unknown dimension.
then i try to do something like this
String [] abc = new string [4]
then i first make a presumption that the size is that in the first column in the second dimension.
abc[0] = String [10][][] inside1;
abc[1] = String [10][][] inside2;
abc[2] = String [10][][] inside3;
abc[3] = String [10][][] inside4;
but still getting error when i compile it.
how can i do the declaration or there got better to done this easy.
if i miss any post in the internet about this. please show me any keyword or link for me to take a look.
What is it that you are trying to implement? Sounds like you instead should use one of the collection classes together with value objects that represent your data.
I think i understand what you are trying to do and its like this:
String[][] value = new String[4][3];
Java doenst have multidimensional arrays, its Arrays Within Arrays.
If you're trying to parse a text file and you know what each column signifies, you should create a new object which contains that data. Arrays of arrays are an unnecessarily painful hack and your code is much more maintainable if you just do what Java is designed to be used for--write a class.
Example for a 10x13 matrix:
String [] [] abd = new String [10] [13];
EDIT: I chose 10x13, because 1x3 doesn't make much sense, being the first value 1.
Why don't you create an Object that has a 'name' property (or 'index' if you prefer), and a 'list' property of type List?
public class YourMultiDimensionalArrayObject {
private int index;
private List<String> vals;
public YourMultiDimensionalArrayObject(int _index) {
index = _index;
}
public void setValues(List<String> _vals) {
vals = _vals;
}
public int getIndex() {
return index;
}
public List<String> getVals() {
return vals;
}
}
You can use ArrayList to store an array of int values of unknown length. You can use an ArrayList> to store an indefinite number of int arrays.
I would create either a List<List<String>> or a Map<String, List<String>>, assuming the values you want to store and look-up by are Strings.