How to fill two-dimensional array using java enhanced loop? - java

Basically, I am trying this, but this only leaves array filled with zeros. I know how to fill it with normal for loop such as
for (int i = 0; i < array.length; i++)
but why is my variant is not working? Any help would be appreciated.
char[][] array = new char[x][y];
for (char[] row : array)
for (char element : row)
element = '~';

Thirler has explained why this doesn't work. However, you can use Arrays.fill to help you initialize the arrays:
char[][] array = new char[10][10];
for (char[] row : array)
Arrays.fill(row, '~');

From the Sun Java Docs:
So when should you use the for-each loop?
Any time you can. It really beautifies your code. Unfortunately, you cannot use it everywhere. Consider, for example, the expurgate method. The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it.

This is because the element char is not a pointer to the memory location inside the array, it is a copy of the character, so changing it will only change the copy. So you can only use this form when referring to arrays and objects (not simple types).

The assignment merely alters the local variable element.

Related

Java: Concatenating not specified number of 2d Arrays dinamically

I know that there were other questions related to this topic.
But this is a little different.
Immagine that you have a program that gets every some amount of time an 2d Object (Object[][]) from the excel and it pass this to one method; this method needs to concatenate this 2d Object, so when it gets a flag that there is no more input, it passes this potentially big 2d object as a result to some other method...
1) You don't know how many excel documents will be sent , so how many 2d object will you get
2) every 2d object can have different num of columns and rows (ok this is not a big problem)
Is there a way in java to concatenate 2d objects into one? Wihout "killing" the memory.
Looking at this accepted anwer
How do you append two 2D array in java properly?
there is an append method, but each time it is called (and in this described case we don't know how many times could be called), it recreates an 2d array, and in my opition is not a best practice for this solution.
Looking at this accepted solution How to concatenate two-dimensional arrays in Java there is used an arraycopy solution, which how i understood is something similar to the previous solution... maybe a little better.
I know that would be possible to use some lists that could somehow rappresents this 2d object, or be parsed at the end in the 2d object, but:
is there any way in java (good practice) to concatenate dinamically unown number of 2d object into 1?
tnx
It look like you need ArrayList< ArrayList < Object > > instead of Object[][]. If you use ArrayList, the different num of columns and rows aren't problems at all, and you not "killing" the memory if you use addAll method. Moreover, you could use a core Java methods to concat ot ArrayLists without create your own manual methods.
For example, you can use something like this:
public List<ArrayList<Object>> concat (List<ArrayList<Object>> list1, List<ArrayList<Object>> list2) {
if(list1.size() > list2.size()) {
List<ArrayList<Object>> listBig = new ArrayList(list1); // or just list1 if we can change list1
List<ArrayList<Object>> listSmall = list2;
} else {
List<ArrayList<Object>> listBig = new ArrayList(list2); // or just list1 if we can change list1
List<ArrayList<Object>> listSmall = list1;
}
for(int i = 0; i < listSmall.size(); i++) {
listBig[i].addAll(listSmall[i]);
}
return listBig;
}

What is the difference between i<=array.length and array.length>i

We've started using netbeans in our Java programming class, after using notepad++ for a while. While iterating through an array list. I used the following code:
for (int i=0; i<=randomarrayhere.length; i++)
Netbeans suggested to flip the position of i and array.length
for (int i=0; randomarrayhere.length>i; i++)
What do we gain by this?
Thanks!
The first would throw an ArrayIndexOutOfBoundsException when i reaches randomarrayhere.length.
Aside from that (if you use i<randomarrayhere.length), there is no difference.
you can either use randomarrayhere.length>i or i<randomarrayhere.length, but don't use randomarrayhere.length>=i or i<=randomarrayhere.length because if you call randomarrayhere[i] anywhere in your forloop you will get an Exception since array indices are zero-based.
An array with 1 item has a length of 1, but the objects index in the array is 0. This throws an index out of bounds error. You can also do x=array.length - 1 and use = in your comparison

How to add an element at the end of an array?

I want to know how to add or append a new element to the end of an array. Is any simple way to add the element at the end? I know how to use a StringBuffer but I don't know how to use it to add an element in an array. I prefer it without an ArrayList or list. I wonder if the StringBuffer will work on integers.
You can not add an element to an array, since arrays, in Java, are fixed-length. However, you could build a new array from the existing one using Arrays.copyOf(array, size) :
public static void main(String[] args) {
int[] array = new int[] {1, 2, 3};
System.out.println(Arrays.toString(array));
array = Arrays.copyOf(array, array.length + 1); //create new array from old array and allocate one more element
array[array.length - 1] = 4;
System.out.println(Arrays.toString(array));
}
I would still recommend to drop working with an array and use a List.
Arrays in Java have a fixed length that cannot be changed. So Java provides classes that allow you to maintain lists of variable length.
Generally, there is the List<T> interface, which represents a list of instances of the class T. The easiest and most widely used implementation is the ArrayList. Here is an example:
List<String> words = new ArrayList<String>();
words.add("Hello");
words.add("World");
words.add("!");
List.add() simply appends an element to the list and you can get the size of a list using List.size().
To clarify the terminology right: arrays are fixed length structures (and the length of an existing cannot be altered) the expression add at the end is meaningless (by itself).
What you can do is create a new array one element larger and fill in the new element in the last slot:
public static int[] append(int[] array, int value) {
int[] result = Arrays.copyOf(array, array.length + 1);
result[result.length - 1] = value;
return result;
}
This quickly gets inefficient, as each time append is called a new array is created and the old array contents is copied over.
One way to drastically reduce the overhead is to create a larger array and keep track of up to which index it is actually filled. Adding an element becomes as simple a filling the next index and incrementing the index. If the array fills up completely, a new array is created with more free space.
And guess what ArrayList does: exactly that. So when a dynamically sized array is needed, ArrayList is a good choice. Don't reinvent the wheel.
The OP says, for unknown reasons, "I prefer it without an arraylist or list."
If the type you are referring to is a primitive (you mention integers, but you don't say if you mean int or Integer), then you can use one of the NIO Buffer classes like java.nio.IntBuffer. These act a lot like StringBuffer does - they act as buffers for a list of the primitive type (buffers exist for all the primitives but not for Objects), and you can wrap a buffer around an array and/or extract an array from a buffer.
Note that the javadocs say, "The capacity of a buffer is never negative and never changes." It's still just a wrapper around an array, but one that's nicer to work with. The only way to effectively expand a buffer is to allocate() a larger one and use put() to dump the old buffer into the new one.
If it's not a primitive, you should probably just use List, or come up with a compelling reason why you can't or won't, and maybe somebody will help you work around it.
As many others pointed out if you are trying to add a new element at the end of list then something like, array[array.length-1]=x; should do. But this will replace the existing element.
For something like continuous addition to the array. You can keep track of the index and go on adding elements till you reach end and have the function that does the addition return you the next index, which in turn will tell you how many more elements can fit in the array.
Of course in both the cases the size of array will be predefined. Vector can be your other option since you do not want arraylist, which will allow you all the same features and functions and additionally will take care of incrementing the size.
Coming to the part where you want StringBuffer to array. I believe what you are looking for is the getChars(int srcBegin, int srcEnd,char[] dst,int dstBegin) method. Look into it that might solve your doubts. Again I would like to point out that after managing to get an array out of it, you can still only replace the last existing element(character in this case).
one-liner with streams
Stream.concat(Arrays.stream( array ), Stream.of( newElement )).toArray();

Copy array without redundancy

I have two arrays in my program. One is full(with redundant items in it). I want to copy all the items to the second empty array without redundancy. The only problem I have is "how to declare size of the second array?" Because Iam not sure how many are the redundant items in the first array.
I would use Set for this, that will remove duplicates from your array and you convert then back to array or another collection of you need that.
Set<Item> withoutDups = new HashSet<Item>(Arrays.asList(yourArray));
//now you have it without duplicates and do whatevet you want with it:-)
Item[] arrayWithoutDups = new Item[withoutDups.size()];
withoutDups.toArray(arrayWithoutDups); // fill the array
Convert string array to list. Use a LinkedHashSet to eliminate duplicates. The LinkedHashSet maintains insertion order along with uniqueness.
Edit: I have removed the List as it is redundant.
String[] words = {"ace", "ace","boom", "crew", "dog", "eon"};
Set<String> hs = new LinkedHashSet<String>(Arrays.asList(words));
String[] mywords=hs.toArray(new String[hs.size()]);
for(int i=0;i<mywords.length;i++)
{
System.out.println("..."+mywords[i]);
}
Arrays are of fixed size. You should use ArrayList in this case.
However, if you have to use an array then you should allocate the size of 2nd array equal to the size of 1st array because it may contain no redundant elements at all.
Use ArrayList which size can be smaller than original array, then create array from it, if needed.
So what's the problem ?
Loop through values in source array, find number of redundant items. Then allocate second array and in next loop copy values.
Complexity of this approach is 2n=O(n)
Since you don't know which item are redundant you need to loop over your array. I suggest that you use temporary List uniqueItemsList to add the items during your loop.
The list will grow as needed.
Then you can get a array with code like this (replace String with your type) :
String uniqueItems[] = new String[uniqueItemsList.size()];
uniqueItems = uniqueItemsList.toArray(uniqueItems);

what does ":" stands for, in a for function

i have this code, and i would like to know what the ":" mean in the function
Element[][] grid = readFile();
for (Element[] ea : grid) {
for (Element e : ea)
System.out.print(e.getChar());
System.out.println();
In terms of a language equivalent, you can think of it as the word "in". You can read it as "for each Element 'e' in 'ea'".
Here's the documentation on that type of loop: http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
When : is used in for, it acts as a for-each loop. Each iteration, the variable after the colon is assigned to the next value in the array.
int[] arr = {1,2,3,4};
for ( arr : num ) {
System.out.print( num + " " );
}
// prints "1 2 3 4 "
It's a for-each comprehension for Collections and Array. It's same as some languages like Python provide in functionality. So when you see a : in a for loop, read as in. For more details see this http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
In your case it's like for ea in grid.
This type of loop is called a 'for-each' loop. The colon (:) is read as 'in'. Basically, this type of for loop is used with collections.
It could be read as:-
for each element x in collection Y{
//do something
}
Here, in each iteration, the element x refers to the respective elements in Collection Y. i.e, in first iteration, x will be Y[0], in second iteration, x will be y[1], so on and so forth till the end.
The advantage is that condition checking and all those stuff need not be written explicitly. It is especially useful when iteration elements in a collection sequentially till the end. This makes iterating over collections quite easier. It is easier than making use of iterators.
In your code, each element of the two dimensional array 'ea' is printed, using a nested for-each loop. Outer loop iterates over each row (a single dimensional array), and inner loop iterates over each element in the respective row.
Refer these:-
For-each loop
Related question in stackoverflow
This is the new enhanced for loop.
You can read it out loud as for each Element ea in grid. It iterates over the elements in grid.
Here is a nice tutorial .
It's simply a divider between the temporary variable and the Iterable or array.
It's called a foreach loop, and basically means:
"For each element ae in Iterable grid, do {...}"
Read more here: The For-Each Loop
Iterable being an array or a list, for example.

Categories