I'm currently desperatly trying to get an ArrayList that I return from a function into a new ArrayList in my main function...
Here are the code snippets:
public static ArrayList<String> permute(String begin, String end) {
ArrayList<String> al=new ArrayList<String>();
//filling bla
return al;
}
and here's where I call the function in the main function:
ArrayList<String> arr =permute("","abc");
arr unfortunately is empty, and I have no idea how to get it to work :(
Thanks in advance
EDIT:
Here's the full code:
import java.util.*;
class Problem24 {
public static ArrayList<String> permute(String begin, String end) {
ArrayList<String> al=new ArrayList<String>();
if (end.length() <= 1) {
String s=begin+end;
al.add(s);
} else {
for (int i = 0; i < end.length(); i++) {
try {
String newString = end.substring(0, i) + end.substring(i + 1);
permute(begin + end.charAt(i), newString);
} catch (StringIndexOutOfBoundsException exception) {
exception.printStackTrace();
}
}
}
return al;
}
public static void main (String[] args)
{
ArrayList<String> arr =permute("","abc");
System.out.println(arr.get(0));
}
}
Your ArrayList is empty but not null which means that the returning part worked. In oder to use the values from the method you need to fill the ArrayList inside the method.
ps: You should use List list = new ArrayList() or
List list = permute("", "abc") which is a simple version of dependency injection and a better design of your program.
You're not adding the items from the recursive calls.
Try adding the al.addAll to your permute call:
al.addAll(permute(begin + end.charAt(i), newString));
before returning the value make sure you are filling the al List
al.add(begin);
al.add(end);
al.add("any other string");
return al;
Obviously something in wrong with the // filling bla part.
I'd start with replacing your code in // filling bla with al.add("TEST"); and see if you even get something out.
Also your method is static and the source array isn't passed in, which suggest that either your code is supposed to permute those strings somehow. Are you possibly acting upon a static array (i.e. permute all elements between begin and end), and the source array is empty?
import java.util.*;
class Problem24
{
public static ArrayList<String> permute(String begin, String end)
{
ArrayList<String> al=new ArrayList<String>();
if (endingString.length() <= 1)
{
String s=begin+end;
al.add(s);
}
else
{
for (int i = 0; i < end.length(); i++)
{
try
{
String newString = end.substring(0, i) + end.substring(i + 1);
al.add(permute(begin + end.charAt(i), newString));
}
catch (StringIndexOutOfBoundsException exception)
{
exception.printStackTrace();
}
}
}
return al;
}
public static void main (String[] args)
{
ArrayList<String> arr = permute("","abc");
System.out.println(arr.get(0));
}
}
hope i corrected it the right way.
You call your method permute recurrently --- but you make no use of what it returns when it returns. In other words, you create a new array each time you call permute, but everything you get in for-loop is lost, as you are not passing it to next permute() calls --- eventually you return an empty array in which you didn't put anything.
Related
Sorry to repeat the question but i am new and looking the others answers didn't help me much.
I'd like to update my arraylist but i get stuck in an error that i cannot solve. Eclipse underlines the word set.
My code is:
private List<List> lists;
public void updateList(int index, string a) throws listException {
for(index = 0; index<list.size(); index++) {
list.get(index);
list.set(index, a);
}
You named the list as lists and trying to access list in the for-loop.
So your for loop should become like this:
for(index = 0; index<lists.size(); index++) {
lists.get(index);
lists.set(index, a);
}
Also it's String and not string and you will have to initialize the list.
So first change:
// Type should be String
private List<String> lists = new ArrayList<>();
And am not sure what is listException.
public void updateList(int index, String a) {
// Your rest of the code.
How to check whether a specific String is present inside ArrayList<String[]>?
Whether I need to iterate each item and check for the string or any specific method for this purpose is present (like ArrayList.contains() )?
Tried ArrayList.contains() but not working in my case.
It is not an ArrayList <String> it is ArrayList<String[]> so this question is not a duplicate one and am asking this for a curiosity whether any special method is present or not
This is a example program to get what you asked for... hope it helps
public static void main(String[] args) {
ArrayList<String []> a = new ArrayList<>();
String b[] = {"not here","not here2"};
String c[] = {"not here3","i'm here"};
a.add(b);
a.add(c);
for (String[] array : a) {// This loop is used to iterate through the arraylist
for (String element : array) {//This loop is used to iterate through the array inside the arraylist
if(element.equalsIgnoreCase("i'm here")){
System.out.println("found");
return;
}
}
}
System.out.println("match not found");
}
You can do it easily with streams:
String contains;
List<String[]> strings;
boolean isPresent = strings.stream().flatMap(Arrays::stream).anyMatch(contains::equals);
Well, you need to traverse whole list and then traverse each array inside it to find the item.
String valToBeSearched="abc";
for(String [] arr: list)
{
for(String str: arr)
{
if(str.equals(valToBeSearched)){ // do your stuff}
}
}
Using Java 8 streams, you can do this:
public boolean containsString(List<String[]> list, String s) {
// Gives you a Stream<String[]>.
return list.stream()
// Maps each String[] to Stream<String> (giving you a
// Stream<Stream<String>>), and then flattens it to Stream<String>.
.flatMap(Arrays::stream)
// Checks if any element is equal to the input.
.anyMatch(Predicate.isEqual(s));
}
You could iterate over the ArrayList with two for-each loops:
import java.util.Arrays;
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String[]> arrayList = new ArrayList<String[]>();
String[] fruit = {"Apple", "Banana"};
String[] pets = {"Cat", "Dog"};
arrayList.add(fruit);
arrayList.add(pets);
System.out.println(Arrays.deepToString(arrayList.toArray())); //[[Apple, Banana], [Cat, Dog]]
System.out.println(arrayListContains(arrayList, "Apple")); //true
System.out.println(arrayListContains(arrayList, "Orange")); //false
}
public static boolean arrayListContains(ArrayList<String[]> arrayList, String str) {
for (String[] array : arrayList) {
for (String s : array) {
if(str.equals(s)) {
return true;
}
}
}
return false;
}
}
Try it here!
Try to take a look at Guava Iterables.concat().
It can be used to flatten Iterable of Iterables, i'm not sure it will work on an Iterable of Array but it's just a little transformation...
If you can flatten your list, you could then use the "contains" method on the result.
I am trying to create a basic for loop that adds the elements of a temporary List to the main ArrayList. This causes my Android App to crash repeatedly.
for (int i = 0; i<tempFavList.size();i++){
Log.v("MyApp",Integer.toString(tempFavList.size()));
favourites.add(tempFavList.get(i).toString());
}
Some debugging showed that tempFavList.size() is equal to 2 before the for loop is called, but goes to infinity when the for loop is called (well at least to +500,000 before the App crashes). The list tempFavList is a List that is pulled from a Parse database using the code tempFavList = currentUser.getList("favourites");
I am fairly confused why the for size of the temporary List is increasing once the for loop is called, as I am not adding any items in the for loop. Any help would be greatly appreciated
You can try:
final int tempSize = tempFavList.size();
for (int i = 0; i < tempSize; i++){
....
}
Ok so here is what I think you are doing 95% of the code I post here is probably what you have
import java.util.ArrayList;
import java.util.List;
public class Temp {
static ArrayList<String> favourites = new ArrayList<String>();
public static void main(String[] args) {
List<String> myGuiltyList= CurrentUser.getList("favourites");
for (int i = 0; i < myGuiltyList.size(); i++) {
System.out.println("myInnocentList size = " + favourites.size());
favourites.add(myGuiltyList.get(i));
if (myGuiltyList.size() == 1000) {
break;
}
}
}
private static class CurrentUser {
public static List<String> getList(String listName) {
favourites.add("1");
favourites.add("2");
favourites.add("3");
if (listName.equals("favourites")) {
return favourites;
}
else return null;
}
}
}
The problem is that the static list you have named favourites is actually the SAME list you get when you call the CurrentUser.getList("favourites"); line.
So they are actually the same list and you add element to the same list and the size of the list increases with every loop and the loop will never stop cos the size of the list will never be smaller than i cos they increase with the same ratio
:D
Use iterators to iterate:
for (Object o : tempFavList){
Log.v("MyApp",Integer.toString(tempFavList.size()));
favourites.add(o.toString());
}
It will most likely throw an exception, if collection is modified while iterating over.
for (Iterator iterator = tempFavList.iterator(); iterator.hasNext();)
{ favourites.add(iterator.next());}
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
I want to remove duplicates e.g.{ {1,2,3}, {2,3,1},{3,2,1},{2,1,3} } are duplicates of {2,3,1} or any one from given 4 sets.for this i converted 2D Integer array into LinkedHashSet which removed duplicates but when i am converting back to array (due to need in algorithm) i am unable to access individual elements.is it possible? if not, what is the other way.if yes what is problem in the code.given below.please resolve.
my own other thinking: as i think through string is it possible?
e.g { {2,3,1},{-3,-2,-4},........... } insert in Set making ArrayList of each 3 element set e.g.{2,3,1},{-3,-2,-4},{3 element}, .....and then parseInt to access individual element as {2},{3},{1},{-3},{-2},{-4},... will it work?
import java.util.*;
class demo
{
Integer[][] orderedpair3k={{1,2,3},{1,3,-2},{2,3,-1},{1,2,3},{1,-3,-2},{2,-3,-1},{1,-2,-3},{1,3,2},{-2,3,-1},{1,-2,3},{1,-3,2},{-2,-3,-1}};
Set<Set<Integer>> r = new LinkedHashSet<Set<Integer>>();
Object[][] a;
public void init_clauses()
{
removeDuplicate();
System.out.println(r);
backToArray();
for(int i=0;i<a.length;i++)
System.out.println(a[0][i]);
}
public void removeDuplicate()
{
int i=orderedpair3k.length;
for(int j=0;j<i;j++)
r.add(new LinkedHashSet<Integer>(Arrays.asList(orderedpair3k[j])));
}
public void backToArray()
{
ArrayList<Set<Integer>> arr=new ArrayList<Set<Integer>>(r);
a = new Object[arr.size()][3];
for(int i=0;i<a.length;i++)
a[i]=arr.toArray(new Object[i]);
}
}
public class sat
{
public static void main(String[] arg){
demo S = new demo();
S.init_clauses();}
}
//in the above code i am unable to access individual element because in the array Set is inserted as Object even i tried using ((Integer)a[i][j]).intValue() i think this is due to Arrays.asList(orderedpair3k[j]) how this problem can be resolve?
Seems quite straightforward:
Integer[][] result = new Integer[r.size()][3];
int c = o;
for (Set<Integer> s : r)
result[c++] = s.toArray(new Integer[3]);