Java array initialization [closed] - java

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
What happens when we print reference variable of array initialization?
int[] it=new int[10];
sop(it);
What is the result?

int[] it = new int[10];
System.out.println(it);
it is an object, hence you are calling println(Object) of PrintStream (System.out), which calls toString() on the passed object internally. The arrays' toString() is similar to Object's toString():
getClass().getName() + "#" + Integer.toHexString(hashCode());
So the output would be something like:
[I#756a7c99
where [ represnts the depth of the array, and I refers to int. 756a7c99 is the value returned from hashCode() as a hex number.
Read Class.getName() JavaDoc.
To print an array, use Arrays.toString(), something like:
int[] it = new int[10];
System.out.println(Arrays.toString(it));
OUTPUT:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Assuming that sop is System.out.println, it will show you a String resulting returned by the toString method. In this case it will be the name of the class + "#" + the hexa of the hashcode.

Something like [I#30c221
It's the memory address of your new array
int[] it=new int[10];
System.out.println(it);

Related

How do I shift the contents of an array? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
For example, I have an array with the following contents:
a, b, c, d, e, f
I want the result to be:
b, c, d, e, f, a
How do I do this?
Use arraycopy :
var t = arr[0];
System.arraycopy(arr, 1, arr, 0, arr.length-1);
arr[arr.length-1] = t;
The javadoc specifies this operation is safe :
If the src and dest arguments refer to the same array object, then the
copying is performed as if the components at positions srcPos through
srcPos+length-1 were first copied to a temporary array with length
components and then the contents of the temporary array were copied
into positions destPos through destPos+length-1 of the destination
array.
Collections.rotate(Arrays.asList(array), -1);
try using ArrayList, it has some nice methods which shifts automatically. try
myArrayList.add(0,myArrayList.remove(myArrayList.size()-1))
LinkedList can do this fast, but you don't need to do this in most cases. Instead, defining a start index is much easier without modifying the content of the array.
For example,
int start = 5;
for (int i=start, j=0; j<arr.length; i++, j++) {
if (i == arr.length) {
i = 0;
}
// do something with arr[i]
}
copying array is another solution, but if you rotate the array frequently, I suggest not to change the content or creating new arrays, by defining a start index, you can change the start point whenever you want.

Access to the boxes of a Matrix [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'd like to create a matrix like this one:
It's the transform of a graph in a matrix where a, b, c and so on are the vertices and the values represent 0 if the vertices are disconnected and 1 if they're connected.
I take two vertices randomply (i.e. c and d) and I'd like to access the value of those vertices in the matrix as M[c][d] and, also, M[d][c].
How can I do this?
If you will use integer indexes instead of letters you will be able to say m[2][3], if the matrix is defined as: int[][] m;
If you need to access the values using string coordinates, probably you should take a look at the Table class from Guava, see: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Table.html.
This way, you will be able to declare your matrix like: Table<String,String,String> and insert values using: put(String rowKey, String columnKey, String value) method and access them using get(String rowKey, String columnKey)
If you trylly want to use letters (chars) as indexes then you'll have to take an alternative approach. You can create your own structure that takes char as an index. Since a two dimensional array can be seen as an array of arrays, you can use a Map or Map objects.
You won't be able to access the objects the way you expect with this, instead you'll have to invoke map.get('c').get('d').
Another approach is to create a sort of "rosetta stone" that translates your char into the corresponding index. This is particulary useful for small graphs, since big ones generate inmense matrices and getting the index there depends on how will you address them. For example:
public class IndexInterpreter {
//Using a switch here to illustrate, you can make your own mapping logic.
public static int getIndex(char letter) {
switch(letter) {
case 'a':
return 0;
case 'b':
return 1;
//the swtich goes on and on...
}
}
}
and then, while calling the matrix you just translate the letters into their corresponding indexes:
int i1 = IndexInterpreter.getIndex('c');
int i2 = IndexInterpreter.getIndex('d');
m[i1][i2]
or, if you like
m[IndexInterpreter.getIndex('c')][IndexInterpreter.getIndex('d')]
matrix would be a 2D array
String[][] matrix = new String[6][7]
you could then populate it using
matrix[1][1] = "1";
To get the cell you want you wuld do
String val = mattix[3][5];
This link may help

Generate Random Letters in Java [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
hey guys this is my problem..
I want to generate random letters in an specific length of a word, but the Starting Letter should corresponds to value of the variable I declare.
Example:
A3 should generate AER
A5 should generate AJIEH
B2 should generate BJ
Working with the variable names will be tedious (although it is possible I suppose through reflection). You could, however, try something like this:
public static String genString(char first, int len) {
String s = "";
for (int i = 1 ; i < len ; i++)
s += (char)(Math.random() * ('Z' - 'A' + 1) + 'A');
return first + s;
}
For example:
System.out.println(genString('A', 4));
Output (one of many possible):
AVGH

recursion parameter issue [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
public void mystery1(int n) {
if (n <= 1) {
System.out.print(n);
} else {
mystery1(n / 2);
System.out.print(", " + n);
}
}
What gives this code for odd numbers. Becuase when we divide it it will not be an integer.
There is not mystery, because result of the integer division in Java is integer.
In Java or most other programming languages, when you divide an integer by an integer, the result will be an integer. If a decimal number occurs, say for example:
5/2=2.5
then, the number before the decimal point will be treated as the integer and 2 will be chosen.
In case you want to explicitly convert the integer into float or double, you can use any of the following conversions:
(float) 3/2;
(double) n/2;
The above explicitly converts it to a decimal.
n / 2, this is an integer division, where the fraction part will be ignored.
System.out.println(3/2); // prints 1
System.out.println(3.0/2); // prints 1.5
System.out.println(3/2.0); // prints 1.5
System.out.println(3.0/2.0); // prints 1.5
Param will rounded to int, for example if param will be 5, the next call the function will be with param 2

Sorting a char array in java [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
How would I sort a char array in Java? I know I can use java.util.Arrays.sort(), but if I manually want to sort it? Using bubble sort or something?
Notice the string is "cab", the sorted result should be "abc". I don't know how to sort this, i know how to sort integers, but i don't know how to sort char arrays.
Here's my code:
String s1 = "cab";
char[] arr;
arr = s1.toCharArray();
//Could use
//java.util.Arrays.sort(arr);
//But want to do it manually using something like bubble sort
s1 = new String(arr);
characters can be directly compared as the comparison operators are overloaded. w>q i.e
arr[1]>arr[0]
is valid and gives true. So just treat them like integers in the bubble sort algorithm.
Using bubble sort or something?
Yes, a bubble sort would work. Or you could use any one of the other well-known sort algorithms; e.g. as listed in this Wikipedia page ... or any good textbook on data structures and algorithms.
(But no, I'm not going to code this for you.)
I have no idea weather this solution is the best way, and to be honest I don't think it is.
But I'v made a little piece of code which sorts an array in the following steps:
Make a for loop that goes from 0 to array.size() * array.size().
Make a index variable (int) which is 0 out side the loop
in the loop add a try catch and catch OutOfBoundsException, in the catch set index to 0.
In the try you get 'index' of your array,
char c = array[index]
And compare to index +1
c.compareTo(array[index +1])
If that's a positive number >0 you switch the two items' positions array[index] and array[index + 1]
If it doesn't make sense to you I can provide a code sample, but not before 2 hours from now, approximately..
This is what I meant:
public static ArrayList<mContact> SortByName(ArrayList<mContact> arr)
{
int i = 0;
for (int o = 0; o < arr.size() * arr.size(); o++)
{
try
{
int c = arr.get(i).getName().compareTo(arr.get(i + 1).getName());
if (c > 0)
{
mContact con = new mContact(arr.get(i).getName());
arr.get(i).setName(arr.get(i+1).getName());
arr.get(i+1).setName(con.getName());
}
i++;
}
catch (IndexOutOfBoundsException ex)
{
i = 0;
}
}
return arr;
}
That sorts the List by the contacts Name in ascending order.
The compareTo Method returns a integer that represents the diffrence of the two strings. and 0 if they are the same!
You can compare ASCII values of each of the characters or convert each of the to int using parseInt and compare their values.

Categories