Having trouble returning truncated copy of array - java

I have created a method that is supposed to create a copy of an array of length up to the number of values stored in the original array. So if my original array is of length 10, and I only have 4 values contained in it, then my copy of that array should be of length 3. Here is my code:
public int[] getArray(){
int[] temp = new int[size];
for(int i = 0; i<size; i++){
temp[i] = a[i];
//System.out.print(temp[i] + " ");
}
return temp;
}
I used the print statement to make sure it copies the array and it does. It prints it out when I call this method in my main method. But when I comment out the print statement and use "return temp" it returns the memory location. How would I print the values in the copied array WITHOUT using the JCF or any built in methods? I must use a return statement and the name of the method must remain exactly the same for the specifications our teacher provided. Any help would be appreciated.

To output a whole array, not just its address, use java.util.Arrays.toString().
System.out.println(java.util.Arrays.toString(getArray()));

Related

Print list of list of integer

I have the following list:
List<List<int[]>> graph;
How can I print the content of graph without using loop? I tried the following 2 methods but all of them failed to print:
int[][] input=new int[][]{{1,2,5},{1,3,6},{2,3,1}};
List<List<int[]>> graph = new ArrayList<>();
for (int i = 0; i <= 3; i++) graph.add(new ArrayList<>());
for (int[] conn : input) {
int city_A = conn[0], city_B = conn[1], price = conn[2];
graph.get(city_A).add(new int[] {city_B, price});
graph.get(city_B).add(new int[] {city_A, price});
}
graph.forEach(s->System.out.println("Output:"+s));
System.out.println(Arrays.deepToString(graph.toArray()));
Output:[[I#1fb3ebeb, [I#548c4f57]
Output:[[I#1218025c, [I#816f27d]
Output:[[I#87aac27, [I#3e3abc88]
Expected output is to print each element without going to new line:
Output: [[1,2], [1,3], [2,0]]
Edit: the original question has changed.
I think what you actually want is a string representation of your graph.Have you tried a simple
System.out.println(graph);
?
Leaving the answer to the original question up, which was how to print all the integers in the inner list without using a traditional for loop.
graph.forEach(innerList -> {
innerList.forEach(s-> System.out.println("Output: "+ s))
});
But why though..
Also the forEach is just the java functional library shorthand for a traditional for loop, so I'm not quite sure what you're gaining here. Hope that helps
Try this.
graph.stream creates a stream of List<int[]>
flatmap(List::stream) takes those lists and creates a single stream of int[]
Arrays.toString takes an array and prints it separated by commas.
Note that printing an array is printing an object. Its default toString is what you see when you print it so it won't work. Arrays.toString() actually iterates over each element and returns a string that is printable.
List<List<int[]>> graph = some list;
graph.stream().flatMap(List::stream)
.forEach(arr->System.out.print(Arrays.toString(arr) + " "));
More on printing arrays
Notice the numeric part (in hex) for printing out this array. The numeric part
comes from the hashCode. Also the [I in front of the first output means a simple int array. [[I signifies an array of int arrays.
int[] arr1 = {1,2};
System.out.println(arr1); // prints [I#4617c264 on my machine
System.out.println(Integer.toHexString(arr1.hashCode()));
int[][] arr2 = {{1,2},{3,4}};
System.out.println(arr2); // prints [[I#36baf30c on my machine

Array of linked lists of arrays for hash table

So I am creating a Hash Table that uses an Array of Linked Lists of Arrays. Let me take a second to explain why this is.
So I have previously implemented Hash Tables by creating an Array, and each element of the array is a Linked List. This way I could quickly look up a LL of 450,000 elements by searching for the hash value first in the array, and searching the elements of this LL. I should add that this is a project for school and I cannot just use the Hash Tables that comes with java.
Now I want to do something similar... but I massive have a LL of Arrays that I need to search. Here each element of the LL is line of a text file, which represented by a 4 element array, where each of the 4 elements is a different string that was tab delimited in the input file. I need to be able to quickly access the 2nd, 3rd, and 4th string that was located in each line, and that is now an element of this array.
So What I want is to be able to create an Array of LL of Arrays... first I will find the sum of the ascii values of the second element of an array. Then I will hash the entire array using this value into by Hash Table. Then when I later need to find this element, I will go to the corresponding element of the array, where I have a list of arrays. I will the search for the 2nd value of each array in the list. If i find the one I want, then I return that array, and use the 3rd and 4th element of this array.
As I said, I have this working fine for an Array of LL, but adding the extra dimension of Arrays inside has thrown me off completely. I think it is mostly just figuring out syntax, since I have successfully initialized a Array of LL of Arrays (public static LinkedList[] RdHashLL) so it appears that Java is okay with this in principal. However, I have no idea how to put elements into the Hash Table, and how to read them out.
Below is my code for a ARRAY OF LINKED LISTS that works FINE. I just need help getting it to work for an ARRAY OF LL OF ARRAYS!
public class TableOfHash{
public static LinkedList<String>[] HashLL;
//HASH FUNCTION - Finds sum of ascii values for string
public static int charSum(String s){
int hashVal = 0;
int size = 1019; //Prime Number around size of 8 char of 'z', (8 chars is amoung largest consistantly in dictionary)
for(int i = 0; i < s.length(); i++){
hashVal += s.charAt(i);
}
return hashVal % size;
}
//CREATE EMPTY HASH TABLE - Creates an array of LL
public static void makeHash(){
HashLL = new LinkedList[1019];
for(int i=0; i<HashLL.length; i++){
HashLL[i] = new LinkedList<String>();
}
}
//HASH VALUES INTO TABLE!
public static void dictionary2Hash(LinkedList<String> Dict){
for(String s : Dict){
HashLL[charSum(s)].add(s);
//Finds sum of char vales of dictionary element i,
//and then word at i to the HashLL at point defined
//by the char sum.
}
//Print out part of Hash Table (for testing! for SCIENCE!)
//System.out.println("HASH TABLE::");
//printHashTab();
}
//SEARCH HashTable for input word, return true if found
public boolean isWord(String s){
if(HashLL[charSum(s)].contains(s)){
wordsfound++;
return true;
}
return false;
}
}
I have made some attempts to change this, but for things like if(HashLL[charSum(s)].contains(s)) which searches the LL at the element returned by charsum(s)... I have no idea how to get it to work when it is a LL of Arrays and not of Strings. I have tired HashLL[charSum(s)].[1].contains(s)), and HashLL[charSum(s)][1].contains(s)), and various other things.
The fact that a Google search for "Array of Linked Lists of Arrays" (with quotes) turns up empty has not helped.
Last bit. I realize there might be another data structure that would do what I want, but unless you believe that a Array of LL of Arrays is a totally hopeless cause, I'd like to get it to work as is.
if you have
LinkedList<String[]>[] hashLL;
you can read a specific String like this (one of many ways)
String str = hashLL[outerArrayIndex].get(listIndex)[innerArrayIndex];
To write into the fields, this is possible (assuming everything is initialized correctly).
String[] arr = hashLL[outerArrayIndex].get(listIndex);
arr[index] = "value";

Understanding Array Indexing in Java

I have a brief question about how Java handles arrays. Below is my code:
//import java.util.Arrays;
import static java.lang.System.out;
public class Arrays
{
public static void main(String[] args)
{
String [][] multiArray = new String[10][8];
int k = 1;
while (k <= 61) {out.print('-'); k++;}
out.println ();
for (int i = 0; i < multiArray.length; i++)
{
for (int j = 0; j < multiArray[i].length; j++)
{
multiArray[i][j] = i + "" + j;
out.print ("| " + multiArray[i][j] + " ");
}
out.println ("|");
}
k = 1;
while (k <= 61) {out.print('-'); k++;}
out.println();
}
}
I understand that you have to create a double "for" loop to print out values for both dimensions and that you have to have:
multiArray[i].length
so that it knows to reference the length of the second dimension. I just don't understand how it works.
What I'm confused about is this: At the very beginning of the program, directly after I declare my array, if I write a statement like:
system.out.println (multiArray.length);
It will print the value of 10, which is the length I declared in the first dimension. If I, however, create some random variable like "int a = 0" or "int idontgetthis = 0" and then I write:
system.out.println (multiArray[a].length);
it somehow knows to print the length of the second dimension, 8. So my question is, how does it know how to do this? It's killing me!! lol
Because multiArray is really an array of arrays. So multiArray[a] is a reference to an object. That object is itself an array. That array has a length (8), and a property called length which can be used to return that length.
Basically, it is a concept confusion, by doing:
String[] array;
you are declaring that you will have an array of Strings with an unknown lenght.
A call to: System.out.println(array.length) at this moment will fail with a compilation error because array is not yet initialized (so the compiler can't know how long it is).
By doing:
String[] array = new String[8]
you declare that you will have and array of String and initialize it, specifying it will have space for 8 Strings, the compiler then allocates space for this 8 Strings.
Something important to notice is that even when the compiler now knows that you will store 8 Strings in your array, it will fill it with 8 nulls.
So a call to System.out.println(array.length) at this point will return 8 (Compiler knows the size) but a call to System.out.println(array[1]) will return a Null Pointer Exception (You have 8 nulls in it).
Now, in the example you presented, you are declaring a bidimensional array, this is, an array that will contain other arrays.
Bidimensional arrays are initialized as String[][] multiarray = new String[10][8]; and the logic is the same as in simple arrays, the new String[10][8]; indicates the lenght of the array that contains the other arrays, and the new String[10][8]; indicates the length of the contained arrays.
So doing system.out.println(multiArray[x].length); after initializing multiarray is translated as "What is the length of the Xth contained array?", which the compiler, thanks to your initialization, now knows is 8 for all the contained arrays, even when they are full of nulls at the moment.
Hope it helps to add a bit more understanding!
You could try looking at it like this.
public class Arrays{
public static class EightStrings {
public String[] strings = new String[8];
}
EightStrings[] tenOfThem = new EightStrings[10];
}

Finding index of duplicate values in an ArrayList

I have an ArrayList which contains duplicate values at diff diff index.
for example {"Indian","American","Chinese","Australian","Indian","Russian","Indian"}
as u can see the value - "Indian" exists at index - 0, 4 & 6.
I need to know all these indexes where "Indian" exists and create an arrayList of that.
Here is my code:
public void filter(){
categoryArray = Arrays.asList(category);
for(String k : category){
//Log.v("filter", filterTerm);
if(k.equals(filterTerm.toLowerCase()))
{
int p = categoryArray.indexOf(k);
Log.v("index of categArr", ""+p);
String id = Integer.toString(p);
indexes.add(id);
}// end of if
}// end of for
Here I get how many times duplicate occurs by getting the size of indexes(ArrayList)
but when I check the values . Its one value at all index since in the method : indexOf() it always brings the index of first value that it finds in the Array.
So if duplicate exists at index - 2,5,7
I get the array size of index as 3.
But the values are {2,2,2,};
This is a situation where an index-based for loop is more appropriate than enhanced for loop that you're using, as what you need to grab is the index.
You can base all your work on the original array rather than converting it to a list, and I suspect you were going for case-insensitive match.
public void filter(){
for(int i=0; i<category.length; i++){
if(category[i].equalsIgnoreCase(filterTerm))
{
String id = Integer.toString(i);
indexes.add(id);
}
}
}
If you have an ArrayList rather than an array, of course similar code will work, but using list.get(i) instead of category[i].
You need to know which index in the array you are currently at, not the first index where it is to be found. To keep track of that, put
int i = 0;
before the loop, and at the very end of the loop put
i++;
Then the variable i tells you where you have found the value, so you can add i to the indexes list.

String array in Java

Would it be possible to get an answer in pseudocode please, guys?
How could I write a method that, in O(n log n), takes a string array and removes null entries.
I appreciate you can't alter the array size which means I need to copy the contents over to a new one but I can only seem to do it with nested for-loops which compresses my algorithm time and would then become O(n^2)
You need to make a copy of the array, but you only need to make a shallow copy, not a deep copy -- the individual strings don't need to be copied. So it would look something like this:
create new output array O
for each string S in the input array I
if S is not null
add S to O
If you're using ArrayLists, you can use this as-is; however, if you're using plain old Java arrays, you can't resize it each time you add an element. So, instead, you'll need to count the number of non-null entries first, then create an output array of the appropriate size, then loop through the input array again.
Your question suggests that you might be looking for a way to avoid allocating a new array. If that's the case, this solution might be what you're looking for. Rather than returning an array of a smaller size, it instead modifies the given array, moving all null references to the end and packing all the Strings at the front. So {"Foo","Bar",null,"Baz"} becomes {"Foo","Bar","Baz",null}, as an example.
public static void packStrings(String[] strArr) {
int writeIndex = 0;
for (String str : strArr)
if (str != null) strArr[writeIndex++] = str;
Arrays.fill(strArr, writeIndex, strArr.length, null);
}
And in psudocode that would be... ah....
function packString(stringArray)
initialize write index to 0
for each string in stringArray
if the string isn't null
write it to stringArray at the write index
advance the write index
set the rest of stringArray at the write index and beyond to null
That's O(n), but more so, that's a mere n array assignments and zero allocations.
You need to keep track of your progress through both arrays. Let a[] be the original array and b[] be a second array of the same size.
initialize acount to 0
initialize bcount = 0
for acount = 0 to a.length - 1
if(array[acount] != null)
b[bcount++] = a[acount]
return b[]
At the end b will contain only bcount + 1 entries which is less than or equal to the length of the array. So optionally you may want to define an array with only bcount elements to return.

Categories