I'm putting 1D Arrays in an Array List
ArrayList<int[]> pairs_ref = new ArrayList();
int[]singlePair_ref = new int [2];
singlePair_ref[0] = 15;
singlePair_ref[1] = 0;
pairs_ref.add(singlePair_ref);
return pairs_ref;
However, an test output on the console only shows Zeros, not the correct values
pairs_ref = object_ref.methodFillsArrayListAsShownAbove();
for (int t = 0;t<pairs_ref.size();t++){
int[]array_ref = pairs_ref.get(t);
System.out.println("Live: "+array_ref[0]+" "+array_ref[1]);
}//endfor
this Version brings the same result
int[]array_ref = new int[2];
for (int t = 0;t<pairs_ref.size();
array_ref = pairs_ref.get(t);
System.out.println("Live: "+array_ref[0]+" "+array_ref[1]);
System.out.println(pairs_ref.get(t));}
Why is this? Is it the putting or the getting of the variables of the ArrayList?
Thanks in Advance!
Daniel
If this is the observed output for you, something else is wrong in your code.
The program below (verbatim copy of the snippets you provided) outputs the expected result:
import java.util.*;
class Test {
public static ArrayList<int[]> methodFillsArrayListAsShownAbove() {
ArrayList<int[]> pairs_ref = new ArrayList();
int[] singlePair_ref = new int[2];
singlePair_ref[0] = 15;
singlePair_ref[1] = 0;
pairs_ref.add(singlePair_ref);
return pairs_ref;
}
public static void main(String[] args) {
List<int[]> pairs_ref = methodFillsArrayListAsShownAbove();
for (int t = 0; t < pairs_ref.size(); t++) {
int[] array_ref = pairs_ref.get(t);
System.out.println("Live: " + array_ref[0] + " " + array_ref[1]);
}// endfor
}
}
Output:
Live: 15 0
Ideone.com demo
Link
Note that as of Java 5 your code can be simplified:
ArrayList<int[]> pairs_ref = new ArrayList<int[]>(); //note the use of generics in the parameter
int[] singlePair_ref = new int [2];
singlePair_ref[0] = 15;
singlePair_ref[1] = 0;
pairs_ref.add(singlePair_ref);
//simplification here
for (int[] arr : pairs_ref){
System.out.println("Live: "+arr[0]+" "+arr[1]);
}
This should work at your system.
Related
import java.util.Random;
import java.util.Scanner;
public class ArrayHelpers{
public static void main(String[] args){
String arr[] = {"M3", "M4", "M5", "M6", "X5M", "M750Li"};
String stockElements[] = {"BMW M2 Coupé","BMW M3 Sedan", "BMW M4 Coupé", "BMW M5 Sedan","BMW M6 Gran Coupé", "BMW X5 M", "BMW X6 M", "M 750Li"};
int size = 7;
printArrayQuantities(arr);
System.out.println(getRandomElement(arr));
System.out.println(getRandomArray(size, stockElements));
}
public static void printArrayQuantities(String[] arr){
int num[] = {2, 1, 3, 3, 5, 1};
for( int i = 0; i < num.length; i++){
System.out.println(arr[i] + " " + num[i]);
}
}
public static String getRandomElement(String[] arr){
int randomNum = 0 + (int)(Math.random() * 6);
return arr[randomNum];
}
public static String[] getRandomArray(int size, String[] stockElements){
String[] randArray = new String[size];
for( int i = 0; i < size; i++){
randArray[i] = getRandomElement(stockElements);
}
return randArray;
}
}
So I'm trying to return an array that has been randomly inserted with elements from stockElements through getRandomElement method. When I'm trying to print that array from line 12 (System.out.println(getRandomArray(size, stockElements));) it produces [Ljava.lang.String;#6d06d69c as output. I'm aware of the .toString() method, but a requirement of my assignment is that I do not use any built in array methods. How exactly would I go about doing this?
A simple solution is just to iterate over it with for each loop.
String[] myArray = getRandomArray(size, stockElements); // this stores a reference of the returned array.
for(String str : myArray){
System.out.println(str);
}
or with for loop if you prefer.
String[] myArray = getRandomArray(size, stockElements); // this stores a reference of the returned array.
for(int i = 0; i < myArray.length; i++){
System.out.println(myArray[i]);
}
Since your function is returning an array, when you try to print the array you should be iterating through each elements with a for/while loop and printing them individually. Since you're trying to print the array variable it instead prints java's handle for it. So try something like this
String[] randomArray = getRandomArray(size, stockElements);
for (String s : randomArray) {
System.out.println(s);
}
Replace System.out.println(getRandomArray(size, stockElements)); with
String [] output = getRandomArray(size, stockElements);
printArrayQuantities(output);
You already have the array returned, just need to assign it:
String[] newArray = getRandomArray(size, stockElements);
But... if you want to just print it go with the below.
Using Java 8:
String.join(delimiter, newArray);
or (for older Java):
StringBuilder builder = new StringBuilder();
for(String s : newArray) {
builder.append(s);
builder.append(delimeter);
}
return builder.toString();
I am trying to sort an ArrayList using a predefined array of indices.
My current example uses a copy of the original ArrayList for sorting and therefore is not scalable for ArrayLists of larger objects
package sortExample;
import java.awt.List;
import java.util.ArrayList;
import java.util.Arrays;
public class sortExample {
public static void main(String[] args) {
String [] str = new String[] {"a","b","c","d"};
ArrayList<String> arr1 = new ArrayList<String>(Arrays.asList(str));
int [] indices = {3,1,2,0};
ArrayList<String> arr2 = new ArrayList(arr1.size());
for (int i = 0; i < arr1.size(); i++) {
arr2.add("0");
}
int arrIndex = 0;
for (int i : indices){
String st = arr1.get(arrIndex);
arr2.set(i, st);
arrIndex++;
}
System.out.println(arr1.toString());
System.out.println(arr2.toString());
}
}
For reusing same data, please see my solution:
public static void main(String[] args) {
String[] strs = new String[]{"a", "b", "c", "d"};
int[] indices = {3, 1, 2, 0};
String tmp;
for (int i = 0; i < strs.length; i++) {
if (i != indices[i]) {
tmp = strs[i];
strs[i] = strs[indices[i]];
strs[indices[i]] = tmp;
indices[indices[i]] = indices[i];
indices[i] = i;
}
}
for (int i : indices) {
System.out.print(i + " ");
}
System.out.println();
for (String str : strs) {
System.out.print(str + " ");
}
}
Output is:
0 1 2 3
d b c a
Alternate reorder in place based on cycles. Note that indices will be changed to {0,1,2,3}. I don't have Java installed (yet), so I converted working C++ code to what I think is proper Java syntax.
for (int i = 0; i < arr1.size(); i++) {
if(i != indices[i]) {
String st = arr1.get(i);
int t = indices[i];
int k = i;
int j;
while(i != (j = indices[k])){
arr1.set(k, arr1.get(j));
indices[k] = k;
k = j;
}
arr1.set(k, st);
indices[k] = k;
}
}
For this specific case {3,1,2,0}, all this does is swap 0 and 3. The longest cycle occurs when the indices are rotated, such as {3 0 1 2}, in which case st=arr1[0], arr1[0] = arr1[3], arr[3] = arr1[2], arr1[2] = arr1[1], arr1[1] = st.
There is a (a little bit) more simple solution:
int [] indices = {3,1,2,0};
ArrayList<String> arr2 = new ArrayList<String>();
for (int i = 0; i < arr1.size(); i++) {
arr2.add(arr1.get(indices[i]));
}
At the below, just use "indices" for a new array.
public class Sorting {
public static void main(String[] args) {
String [] str = new String[] {"a","b","c","d"};
int [] indices = {3,1,2,0};
String sorted [] = new String [str.length] ;
int i = 0;
for (String string : str) {
sorted[indices[i]] = string;
i++;
}
for (String string : sorted) {
System.out.print(string + " ");
}
}
}
prints: d b c a
Whats the nicest way to fill up following array:
From main:
String[][] data = new String[x][3];
for(int a = 0; a < x; a++){
data[a] = someFunction();
}
Function I am using..:
public String[] someFunction(){
String[] out = new String[3];
return out;
}
Is it possible to do something like this? Or do I have to fill it with for-loop?
With this code im getting error "non-static method someFunction() cannot be refferenced from static content ---"(netbeans) on line data[a] = someFunction();
You have to specify how many rows your array contains.
String[][] data = new String[n][];
for(int i = 0; i < data.length; i++){
data[i] = someFunction();
}
Note that someFunction can return arrays of varying lengths.
Of course, your someFunction returns an array of null references, so you still have to initialize the Strings of that array in some loop.
I just noticed the error you got. Change your someFunction to be static.
Change your someFunction() by adding "static".
You also should consider using an ArrayList for such tasks, those are dynamic and desinged for your purpose (I guess).
public static void main(String[] args){
int x = 3;
String[][] data = new String[x][3];
for(int a = 0; a < x; a++){
data[a] = someFunction();
}
}
public static String[] someFunction(){
String[] out = new String[3];
return out;
}
Greetings Tim
import java.util.ArrayList;
public class BubbleSort {
// the sort method takes in an ArrayList of Strings, sorts
// them in ascending number of characters, and returns a new
// ArrayList of Strings which is already sorted. This method
// does NOT modify the original ArrayList passed in.
public ArrayList<String> sort(ArrayList<String> a){
ArrayList<String> sortingList = new ArrayList<String>();
sortingList = a;
String test = "";
String test2 = "";
int length = 0;
int length2 = 0;
for(int j =0; j<a.size(); j++){
for (int i =0; i<sortingList.size()-1; i++){
test = a.get(i);
test2 = a.get(i+1);
length = test.length();
length2 = test2.length();
if(length2<length){
sortingList.set(i,test2);
sortingList.set(i+1,test);
}
}
}
return sortingList;
}
}
=================================MAIN METHOD=====================================
import java.util.ArrayList;
import java.util.Scanner;
public class BubbleSortTest {
public static void main(String[] args) {
ArrayList<String> inputs = new ArrayList<String>();
// get inputs from user
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of Strings to enter: ");
int no = sc.nextInt();
sc.nextLine(); // clears buffer in Scanner
for (int i = 0; i < no; i++){
System.out.print("Enter String number " + i + ": ");
inputs.add(sc.nextLine()); // add input into ArrayList
}
// invoke the sort method to see if it works
BubbleSort bs = new BubbleSort();
ArrayList<String> sortedInputs = bs.sort(inputs);
// print out the Strings in sortedInputs
System.out.println("Sorted sequence:");
for (int i = 0; i < sortedInputs.size(); i++){
System.out.println(sortedInputs.get(i));
}
// print out the Strings in the original inputs
System.out.println("Original sequence:");
for (int i = 0; i < inputs.size(); i++){
System.out.println(inputs.get(i));
}
}
}
input example
121234256464534
1123123
123141243124124
123
my sorting sequence &
original sequence are both amended in ascending sequence even though I created a new arraylist to return
while ensuring I did not make any changes to the original one.
Thanks in advance
sortingList = a;
Both references, sortingList and a are pointing to the same ArrayList object
Check this question to see how to see how to clone the list: How to clone ArrayList and also clone its contents?
Just remove this line from your code,
ArrayList<String> sortingList = new ArrayList<String>();
sortingList = a; //REMOVE THIS LINE
As you are assigning a new arraylist object just before but in the next line you are storing the reference to original object in sortingList object.
If you want to copy all the elements to sortingList then look at Evans Post but in your example you do not need it as you are assigning the test and test2 variables from original Array supplied.
As Axel pointed, use:
ArrayList<String> sortingList = new ArrayList<String>(a);
With that change, in your BubbleSort class, you are still referencing strings from "a" array, hence they are not being sorted properly. To fix, change:
test = a.get(i);
test2 = a.get(i+1);
to
test = sortingList.get(i);
test2 = sortingList.get(i+1);
Full code:
public ArrayList<String> sort(ArrayList<String> a){
//As Axel pointed, use:
ArrayList<String> sortingList = new ArrayList<String>(a);
String test = "";
String test2 = "";
int length = 0;
int length2 = 0;
for(int j =0; j<sortingList.size(); j++){
for (int i =0; i<sortingList.size()-1; i++){
//reference "sortingList" array instead of "a" array
test = sortingList.get(i);
test2 = sortingList.get(i+1);
length = test.length();
length2 = test2.length();
if(length2<length){
sortingList.set(i,test2);
sortingList.set(i+1,test);
}
}
}
return sortingList;
}
I have an arraylist, say arr. Now this arraylist stores numbers as strings. now i want to convert this arraylist to integer type. So how can i do that???
ArrayList arr = new ArrayList();
String a="Mode set - In Service", b="Mode set - Out of Service";
if(line.contains(a) || line.contains(b)) {
StringTokenizer st = new StringTokenizer(line, ":Mode set - Out of Service In Service");
while(st.hasMoreTokens()) {
arr.add(st.nextToken());
}
}
Since you're using an untyped List arr, you'll need to cast to String before performing parseInt:
List<Integer> arrayOfInts = new ArrayList<Integer>();
for (Object str : arr) {
arrayOfInts.add(Integer.parseInt((String)str));
}
I recommend that you define arr as follows:
List<String> arr = new ArrayList<String>();
That makes the cast in the conversion unnecessary.
run the below code,i hope it meets you requirement.
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
ArrayList<String> strArrayList= new ArrayList<String>();
strArrayList.add("1");
strArrayList.add("11");
strArrayList.add("111");
strArrayList.add("12343");
strArrayList.add("18475");
int[] ArrayRes = new int[strArrayList.size()];
int i = 0;
int x = 0;
for (String s : strArrayList)
{
ArrayRes[i] = Integer.parseInt(s);
System.out.println(ArrayRes[i]);
i++;
}
}
}
Output:
1
11
111
12343
18475
To convert to an integer array, you will input as a string array then go through each one and change it to an int.
public int[] convertStringArraytoIntArray(String[] sarray) throws Exception {
if (sarray != null) {
//new int for each string
int intarray[] = new int[sarray.length];
//for each int blah blah to array length i
for (int i = 0; i < sarray.length; i++) {
intarray[i] = Integer.parseInt(sarray[i]);
}
return intarray;
}
return null;
}
final List<String> strs = new ArrayList();
strs.add("1");
strs.add("2");
Integer[] ints = new Integer[strs.size()];
for (int i = 0; i<strs.size(); i++){
ints[i] = Integer.parseInt(strs.get(i));
}
use the Integer.parseInt() method.
http://www.java2s.com/Code/Java/Language-Basics/Convertstringtoint.htm
If you know that you have an arraylist of string but in your you wil use the same list as list of integer so better while initializing array list specify that the array list must insert only int type of data
instead of writing ArrayList arr = new ArrayList();
you could have written ArrayList<Integer> arr = new ArrayList<Integer>();
Alternate solution
If you want to convert that list into Integer ArrayList then use following code
How to convert String ArrayList into ArrayList of int
ArrayList<String> oldList = new ArrayList<String>();
oldList.add(""+5);
oldList.add(""+5);
ArrayList<Integer> newList = new ArrayList<Integer>(oldList.size());
for (String myInt : oldList) {
newList.add(Integer.parseInt(myInt));
}