Display ArrayList of char in Java - java

I am working on the first part of a String permutation problem and I am just looping over the first char of a string and swap it with every following char of that same String. I initialized an empty ArrayList to store all of those permutations called listeFinale. When I am printing that ArrayList, I am getting a collection of object and not values ([[C#61bbe9ba, [C#61bbe9ba, [C#61bbe9ba, [C#61bbe9ba]), how can I print each char stored in the ArrayList?
import java.util.ArrayList;
import java.util.List;
public class checkPermu {
public static void main(String[] args) {
String myString = "aabc";
applyPermu(myString);
}
public static void applyPermu(String toCheck){
char[] newString = toCheck.toCharArray();
List listeFinale = new ArrayList();
for(int i = 0 ; i < newString.length ; i ++){
char temp = newString[0];
newString[0] = newString[i];
newString[i] = temp;
listeFinale.add(newString);
System.out.println(listeFinale);
}
}
}

First of all, don't use raw types for your List please.. Change:
List listeFinale = new ArrayList();
to:
List<char[]> listeFinale = new ArrayList<>();
As for your actual problem. Those values you see are the default toString() outputs of your inner character-arrays. You could iterate over your list, and call the java.util.Arrays.toString(char[]) method for them like this:
listeFinale.forEach(arr -> System.out.println(Arrays.toString(arr)));
Or, if you want to print them back as String again, use new String(char[]):
listeFinale.forEach(arr -> System.out.println(new String(arr)));
Try it online.

Related

Java comparing two arrays with different structures but some similar items

I would like to compare two arrays. I have the following
ArrayList<String> time_durations = new ArrayList<String>();
time_durations.add("1200-1304")
time_durations.add("6-7")
Then the other array has the following structure
ArratList<FetchedData> apiresult = new ArrayList<FetchedData>();
apiresult.add(new FetchedData("1200-1304", //an array of data))
The class fetched data has
class FetchedData{
private String duration_range;
private ArrayList data;
//then setters and getters
//and also a constructor
}
So i want to compare the two arrays and get all items contained in time_durations but not in apiresult
Samples of them both in a json format is
time_durations = ["1200-1304", "6-7"]
apiresult = [{duration_range:"1200-1304", data:["item1", "item 2"]}
So by comparison i expect it to return the item in array time_durations6-7 that is index 1
So i have tried
if (Arrays.equals(time_durations, apiresult)) {
//this throws an error
}
But the above attempt doesnt work and am stuck.How do i achieve this?
I have checked on This question but still fails
Your code doesn't work as you expected because the first ArrayList is an array of String and the second is an Array of FetchedData. You basically try to compare two ArrayList of different type and this return false by default.
If you want to reach the goals you must map the ArrayList of FetchedData into an ArrayList of String and with Java8 it is possible to do this with a Map function and after you are enable to comparing the two array
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static java.util.stream.Collectors.toList;
import static org.junit.Assert.assertArrayEquals;
public class TestClass {
#Test
public void arrayListComparation(){
List<String> expected = Arrays.asList("6-7");
ArrayList<String> time_durations = new ArrayList<String>();
time_durations.add("1200-1304");
time_durations.add("6-7");
ArrayList<FetchedData> apiresult = new ArrayList<>();
List<String> data = Arrays.asList("item1","item2");
apiresult.add(new FetchedData("1200-1304", data));
List<String> apiResultDurationRanges = apiresult.stream().map(FetchedData::getDuration_range).collect(toList());
time_durations.removeAll(apiResultDurationRanges);
assertArrayEquals(time_durations.toArray(),expected.toArray());
}
}
In this example you have on time_durations all element that not appear into apiResult
Iterate over the API results, get each duration and put them into a set. Remove the elements of the set from the list.
Set<String> apiDurations = apiresult.stream()
.map(FetchedData::getDuration)
.collect(Collectors.toSet());
time_durations.removeAll(apiDurations);
You can use Collection.removeAll:
List<String> apiResult_durations = apiresult.stream()
.map(FetchedData::getDuration_range)
.collect(Collectors.toList());
time_durations.removeAll(apiResult_durations);
After this code, time_durations is only [6-7]
Important to note that this will modify time_durations inline.
If you'd rather not modify it inline, then you can make a copy:
List<String> time_durations_copy = new ArrayList<>(time_durations);
time_durations_copy.removeAll(apiResult_durations);
I think you need the operation of set difference.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> time_durations = new ArrayList<String>();//The list with some elements
ArrayList<String> otherList = new ArrayList<String>();//Another list
ArrayList<String> difference = new ArrayList<String>();//The result
time_durations.add("1200-1304");//Add some data
time_durations.add("6-7");
otherList.add("1200-1304");
for (int i = 0; i < time_durations.size(); i++) {
if (!otherList.contains(time_durations.get(i))) {
difference.add(time_durations.get(i)); // get all items contained in time_durations but not in apiresult
}
}
for (String string : difference) {
System.out.println(string);
}
}
}

Items in list are Overwritten when adding new items

I was wondering if you could help me with this problem, I'm stuck for a day in trying to solve this one. So basically what I want to do is have a list that will contain an array of an array.
I have this initialization
List<double[][]> points = new ArrayList<double[][]>();
I add the elements this way:
points.add(existing.Foods);
My beeColony class contains the data that I want to add:
public class beeColony{
double Foods[][]=new double[FoodNumber][D];
....
}
And here's how I declare an instance of it:
public beeColony existing=new beeColony();
Here's a snippet of the code:
for(run=0;run<existing.runtime;run++)
{
for (iter=0;iter<existing.maxCycle;iter++)
points.add(existing.Foods);
}
What happens is that when I output all the items the list, it only contains the last added items.
for example:
Foods = {(0,0), (1,1), (2,2), (3,3)}
points.add(Foods);
Foods = {(4,4), (5,5), (6,6), (7,7)}
points.add(Foods);
The way that I understand it is that
points.get(0)[0] should countain 0,0 and so on and points.get(1)[0] should contain 4,4 and so on. But what happens is points.get(0) also has the same values as points.get(1)
Collections like ArrayList<X> contain references to X objects, like one end of a string the other end of which is "tied" to the object itself, i.e., where the data resides.
This is also true for arrays like double[][].
What you do is to copy and store the reference end repeatedly, but at the other end there is one and the same double[][]. You can change the contents of that array, but all stored string ends lead to the same array object.
You must create new copies of that array to hold different array values. If you create another BeeColony, it will have another foods array. Otherwise, use new double[m][n] and copy the values. This is how:
double[][] d = { {1,2}, {3,4}, {5,6} };
// create the vector of (still missing) rows:
double[][] copy = new double[d.length][];
for( int row = 0; row < d.length; ++row ){
// create another row of appropriate length:
copy[row] = new double[d[row].length];
// copy the element values
System.arraycopy( d[row], 0, copy[row], 0, d[row].length );
}
PS: You should stick to Java conventions. Classe names are written in camel case starting with an upper case letter; variables and methods should start with a lower case letter. Loops should declare the loop counter inside the for: for( int run = 0;... ). Avoid public for class fields; code getters and setters to access private class fields.
You could use combination of array and iterator to get the work done,
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
public class listerr {
static int getrandom(){
Random r = new Random();
int next = r.nextInt(100);
return next;
}
static double[][] getarr(){
double[][] arr = {{getrandom(),getrandom()}, {getrandom(),getrandom()},
{getrandom(),getrandom()}, {getrandom(),getrandom()}};
return arr;
}
public static void main(String[] args) {
List<double[][]> points = new ArrayList<double[][]>();
for(int run=0;run<3;run++)
{
double[][] arr = getarr();
points.add(arr);
}
Iterator itr = points.iterator();
while(itr.hasNext()){
double[][] dbl = (double[][]) itr.next();
for (int i=0;i<4;i++)
{ for (int j=0;j<2;j++){
System.out.println(dbl[i][j]);
}
}
}
}
}

'transferring' StringBuilder contents to a new ArrayList in java

If I have two class constants:
List<String> workingList= new ArrayList<String>();
StringBuilder holder = new StringBuilder(50);
both residing within, call it class StringParser and primary method readStuff()...
public class StringParser{
public void readStuff(){
//parsing logic and adding <String> elements to
//said workingList...
}//end of method readStuff
followed by a method where I inspect the contents of workingList...
public String someReaderMethod()
{
int ind = 0;
for(int i = 0; i < workingList.size();i++)
{
if(workingList.get(i).contains(someExp))
{
workingList.remove(ind);
holder.append(workingList.get(i).toString());
}
else
{
++ind;
}
}
return holder.toString();
}
...given that StringBuilder holder now contains what workingList has removed, is there a way I can 'pass' the contents of StringBuilder to a new ArrayList?
Is there a reason why you want to use a StringBuilder? You can directly insert the values into a new ArrayList. I think you could do it in a simpler way.
List<String> discardedList = new ArrayList<String>();
public void readStuff() {}
public static List<String> someReaderMethod()
{
for(int i = 0; i < workingList.size(); i++)
{
if(workingList.get(i).contains(someExp))
{
discardedList.add(workingList.get(i));
workingList.remove(i);
}
}
return discardedList;
}
You will need a deliminator to parse string and then you can use Split method and convert String[] to ArrayList.
holder.append(tempList.get(i));
holder.append(";");//Deliminator
Now when you have to use it you need to do
String[] strings =holderString.split(";");
List<String> list = Arrays.asList(strings);
While appending your List elements to your StringBuilder object, you need to append an extra delimiter after every append..
Later on, you can split the String in StringBuilder on that delimiter, and then convert your String array thus obtained to an ArrayList..

Java, getter for array values (array dynamically defined)

I have a series of String[] arrays which are list of words. Something like:
String[] ListOne = new String[100];
String[] ListTwo = new String[100];
/*And so on with other lists */
ListOne[0] = "word00";
ListOne[1] = "word01";
/*And so on till*/
ListLast[99] = "word 99 from last list";
Now I want a function for each list that, given a number returns the corresponding element (word):
public String GetFromListOne(int key) { return ListOne[key];}
Is there a way to avoid manually writing each of this getter functions?
In PHP, for example, I would just use the magic method __call,
or pass as an argument with the list name and reference it dynamically.
Is there a way to do something similar in Java?
Or an alternative strategy to achieve the same result?
You should look into inheritance.
What you basically must do is define an interface (or extend a List class)
public interface ListTest{
//**Gets keys from lists*//
GetFromListOne(int key);
}
then
public class Listone implements ListTest{
/** methods **//
GetFromListOne(int key);
/** methods **//
}
Have fun extending
http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html
You could use a 2 dimensional array, or a list of arrays and have your function take 2 parameters. One for the array that you want and the other for the element in the array.
2 dimensional array:
String[][] ListN = new String[100,100];
String getFromList(int n, int key) {
return ListN[n][key];
}
Or list of arrays:
List<String[]> listOfArrays = new ArrayList<String[]>();
listOfArrays.add(new String[100]);
listOfArrays.add(new String[100]);
String getFromList(int n, int key) {
return listOfArrays.get(n)[key];
}
Could you have a function that takes as input the key and the list number:
public String GetFromListOne(int list, int key) {
switch(list):
case 1:
return ListOne[key];
break;
case 2:
return ListTwo[key];
break;
...
}
or even better make an array of arrays:
String[][] ListOfLists = new String[10];
ListOfLists[0] = new String[100];
...
public String GetFromList(int list, int key) {
return ListOfLists[list][key];
}
Otherwise I don't know of a function to override like __call
String[] ListFour=new String[100];
String[] ListTwentyThree=new String[100];
String[] ListNine=new String[100];
String[] ListOne=new String[100];
Hashtable<Integer,String[]> yourlist=new Hashtable<Integer,String[]>();
yourlist.put(4, ListFour);
yourlist.put(23, ListTwentyThree);
yourlist.put(9, ListNine);
yourlist.put(1, ListOne);
System.out.println(yourlist.get(4)[5]);//fifth string in ListFour
System.out.println(yourlist.get(23)[51]);//fifty first string in List23
System.out.println(yourlist.get(9)[1]);//first stringin ListNine
another version:
Hashtable<Object,String[]> yourlist=new Hashtable<Object,String[]>();
yourlist.put("two multiplied by two", ListFour);
yourlist.put(23, ListTwentyThree);
yourlist.put(0.03, ListNine);
yourlist.put(true, ListOne);
System.out.println(yourlist.get("two multiplied by two")[5]);//fifth string in ListFour
System.out.println(yourlist.get(23)[51]);//fifty first string in List23
System.out.println(yourlist.get(true)[1]);//first stringin ListNine
Based in the __call PHP method, you can achieve this implementing a method that receives the list and the index, and using generics you can get something like this.
public class Utility {
public <T> T getElementFromArray(T[] array, int index) {
if (index >= array.length || index < 0) return null;
return array[index];
}
}
The pitfall of this method is that can't be used for primitive array holders, like int[]. The solution for these cases would be using the wrapper classes for primitive types.
public static void main(String[] args) {
Utility u = new Utility();
String[] ss = new String[2];
ss[0] = "Hello";
ss[1] = "world!";
System.out.println(u.getElementFromArray(ss, 0));
System.out.println(u.getElementFromArray(ss, 1));
int[] ii = new int[2];
ii[0] = 5;
System.out.println(u.getElementFromArray(ii, 0)); //compile error
//Solution: use wrapper classes
Integer[] ii2 = new Integer[2];
ii2[0] = 5;
System.out.println(u.getElementFromArray(ii2, 0));
}
Try this code
List<String[]> lists = new ArrayList<String[]>();
public String getFromLists(int key) {
List<String> res = new ArrayList<String>();
for (String[] s: lists){
res.add(s[key]);
}
return res.get(key);
}
or better
public String getFromLists(int key) {
return lists.get(key)[key];
}

Passing a string array as a parameter to a function java

I would like to pass a string array as a parameter to a function. Please look at the code below
String[] stringArray = {'a', 'b', 'c', 'd', 'e'};
functionFoo(stringArray);
Instead of:
functionFoo('a', 'b', 'c', 'd', 'e');
but if I do this I am getting an error stating that convert String[] into String. I would like to know if it is possible to pass the values like that or what is the correct way to do it.
How about:
public class test {
public static void someFunction(String[] strArray) {
// do something
}
public static void main(String[] args) {
String[] strArray = new String[]{"Foo","Bar","Baz"};
someFunction(strArray);
}
}
All the answers above are correct. But just note that you'll be passing the reference to the string array when you pass like this. If you make any modifications to the array in your called function, it will be reflected in the calling function also.
There is another concept called variable arguments in Java which you can look into. It basically works like this. Eg:-
String concat (String ... strings)
{
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < strings.length; i++)
sb.append (strings [i]);
return sb.toString ();
}
Here we can call the function like concat(a,b,c,d) or any number of params you want.
More Info: http://today.java.net/pub/a/today/2004/04/19/varargs.html
I believe this should be the way this is done...
public static void function(String [] array){
...
}
And the calling will be done like...
public void test(){
String[] stringArray = {"a","b","c","d","e","f","g","h","t","k","k","k","l","k"};
function(stringArray);
}
look at familiar main method which takes string array as param
More than likely your method declaration is incorrect. Make sure the methods parameter is of type String array (String[]) and not simply String and that you use double quotes around your strings in the array declaration.
private String[] stringArray = {"a","b","c","d","e","f","g","h","t","k","k","k"};
public void myMethod(String[] myArray) {}
Feel free to use this how ever you like.
/*
* The extendStrArray() method will takes a number "n" and
* a String Array "strArray" and will return a new array
* containing 'n' new positions. This new returned array
* can then be assigned to a new array, or the existing
* one to "extend" it, it contain the old value in the
* new array with the addition n empty positions.
*/
private String[] extendStrArray(int n, String[] strArray){
String[] old_str_array = strArray;
String[] new_str_array = new String[(old_str_array.length + n)];
for(int i = 0; i < old_str_array.length; i++ ){
new_str_array[i] = old_str_array[i];
}//end for loop
return new_str_array;
}//end extendStrArray()
Basically I would use it like this:
String[] students = {"Tom", "Jeff", "Ashley", "Mary"};
// 4 new students enter the class so we need to extend the string array
students = extendStrArray(4, students); //this will effectively add 4 new empty positions to the "students" array.
I think you forget to register the parameter as String[]
please check the below code for more details
package FirstTestNgPackage;
import java.util.ArrayList;
import java.util.Arrays;
public class testingclass {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.out.println("Hello");
int size = 7;
String myArray[] = new String[size];
System.out.println("Enter elements of the array (Strings) :: ");
for(int i=0; i<size; i++)
{
myArray[i] = "testing"+i;
}
System.out.println(Arrays.toString(myArray));
ArrayList<String> myList = new ArrayList<String>(Arrays.asList(myArray));
System.out.println("Enter the element that is to be added:");
myArray = myList.toArray(myArray);
someFunction(myArray);
}
public static void someFunction(String[] strArray)
{
System.out.println("in function");
System.out.println("in function length"+strArray.length );
System.out.println(Arrays.toString(strArray));
}
}
just copy it and past... your code.. it will work.. and then you understand how to pass string array as a parameter ...
Thank you

Categories

Resources