Writing a method with ArrayList of strings as parameters - java

I am trying to write a method that takes an ArrayList of Strings as a parameter and that places a string of four asterisks in front of every string of length 4.
However, in my code, I am getting an error in the way I constructed my method.
Here is my mark length class
import java.util.ArrayList;
public class Marklength {
void marklength4(ArrayList <String> themarklength){
for(String n : themarklength){
if(n.length() ==4){
themarklength.add("****");
}
}
System.out.println(themarklength);
}
}
And the following is my main class:
import java.util.ArrayList;
public class MarklengthTestDrive {
public static void main(String[] args){
ArrayList <String> words = new ArrayList<String>();
words.add("Kane");
words.add("Cane");
words.add("Fame");
words.add("Dame");
words.add("Lame");
words.add("Same");
Marklength ish = new Marklength();
ish.marklength4(words);
}
}
Essentially in this case, it should run so it adds an arraylist with a string of "****" placed before every previous element of the array list because the lengths of the strings are all 4.
BTW
This consists of adding another element
I am not sure where I went wrong. Possibly in my for loop?
I got the following error:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at Marklength.marklength4(Marklength.java:7)
at MarklengthTestDrive.main(MarklengthTestDrive.java:18)
Thank you very much. Help is appreciated.

Let's think about this piece of code, and pretend like you don't get that exception:
import java.util.ArrayList;
public class Marklength {
void marklength4(ArrayList <String> themarklength){
for(String n : themarklength){
if(n.length() ==4){
themarklength.add("****");
}
}
System.out.println(themarklength);
}
}
Ok, so what happens if your list just contains item.
You hit the line if(n.length() ==4){, which is true because you are looking at item, so you go execute its block.
Next you hit the line themarklength.add("****");. Your list now has the element **** at the end of it.
The loop continues, and you get the next item in the list, which happens to be the one you just added, ****.
The next line you hit is if(n.length() ==4){. This is true, so you execute its block.
You go to the line themarklength.add("****");, and add **** to the end of the list.
Do we see a bad pattern here? Yes, yes we do.
The Java runtime environment also knows that this is bad, which is why it prevents something called Concurrent Modification. In your case, this means you cannot modify a list while you are iterating over it, which is what that for loop does.
My best guess as to what you are trying to do is something like this:
import java.util.ArrayList;
public class Marklength {
ArrayList<String> marklength4(ArrayList <String> themarklength){
ArrayList<String> markedStrings = new ArrayList<String>(themarklength.size());
for(String n : themarklength){
if(n.length() ==4){
markedStrings.add("****");
}
markedStrings.add(n);
}
System.out.println(themarklength);
return markedStrings;
}
}
And then:
import java.util.ArrayList;
public class MarklengthTestDrive {
public static void main(String[] args){
ArrayList <String> words = new ArrayList<String>();
words.add("Kane");
words.add("Cane");
words.add("Fame");
words.add("Dame");
words.add("Lame");
words.add("Same");
Marklength ish = new Marklength();
words = ish.marklength4(words);
}
}

This...
if(n.length() ==4){
themarklength.add("****");
}
Is simply trying to add "****" to the end of the list. This fails because the Iterator used by the for-each loop won't allow changes to occur to the underlying List while it's been iterated.
You could create a copy of the List first...
List<String> values = new ArrayList<String>(themarklength);
Or convert it to an array of String
String[] values = themarklength.toArray(new String[themarklength.size()]);
And uses these as you iteration points...
for (String value : values) {
Next, you need to be able to insert a new element into the ArrayList at a specific point. To do this, you will need to know the original index of the value you are working with...
if (value.length() == 4) {
int index = themarklength.indexOf(value);
And then add a new value at the required location...
themarklength.add(index, "****");
This will add the "****" at the index point, pushing all the other entries down
Updated
As has, correctly, been pointed out to me, the use of themarklength.indexOf(value) won't take into account the use case where the themarklength list contains two elements of the same value, which would return the wrong index.
I also wasn't focusing on performance as a major requirement for the providing a possible solution.
Updated...
As pointed out by JohnGarnder and AnthonyAccioly, you could use for-loop instead of a for-each which would allow you to dispense with the themarklength.indexOf(value)
This will remove the risk of duplicate values messing up the index location and improve the overall performance, as you don't need to create a second iterator...
// This assumes you're using the ArrayList as the copy...
for (int index = 0; index < themarklength.size(); index++) {
String value = themarklength.get(index);
if (value.length() == 4) {
themarklength.add(index, "****");
index++;
But which you use is up to you...

The problem is that in your method, you didn't modify each string in the arraylist, but only adds 4 stars to the list. So the correct way to do this is, you need to modify each element of the arraylist and replace the old string with the new one:
void marklength4(ArrayList<String> themarklength){
int index = 0;
for(String n : themarklength){
if(n.length() ==4){
n = "****" + n;
}
themarklength.set(index++, n);
}
System.out.println(themarklength);
}
If this is not what you want but you want to add a new string "**" before each element in the arraylist, then you can use listIterator method in the ArrayList to add new additional element before EACH string if the length is 4.
ListIterator<String> it = themarklength.listIterator();
while(it.hasNext()) {
String name = it.next();
if(name.length() == 4) {
it.previous();
it.add("****");
it.next();
}
}
The difference is: ListIterator allows you to modify the list when iterating through it and also allows you to go backward in the list.

I would use a ListIterator instead of a for each, listiterator.add likely do exactly what you want.
public void marklength4(List<String> themarklength){
final ListIterator<String> lit =
themarklength.listIterator(themarklength.size());
boolean shouldInsert = false;
while(lit.hasPrevious()) {
if (shouldInsert) {
lit.add("****");
lit.previous();
shouldInsert = false;
}
final String n = lit.previous();
shouldInsert = (n.length() == 4);
}
if (shouldInsert) {
lit.add("****");
}
}
Working example

Oh I remember this lovely error from the good old days. The problem is that your ArrayList isn't completely populated by the time the array element is to be accessed. Think of it, you create the object and then immediately start looping it. The object hence, has to populate itself with the values as the loop is going to be running.
The simple way to solve this is to pre-populate your ArrayList.
public class MarklengthTestDrive {
public static void main(String[] args){
ArrayList <String> words = new ArrayList<String>() {{
words.add("Kane");
words.add("Cane");
words.add("Fame");
words.add("Dame");
words.add("Lame");
words.add("Same");
}};
}
}
Do tell me if that fixes it. You can also use a static initializer.

make temporary arraylist, modify this list and copy its content at the end to the original list
import java.util.ArrayList;
public class MarkLength {
void marklength4(ArrayList <String> themarklength){
ArrayList<String> temp = new ArrayList<String>();
for(String n : themarklength){
if(n.length() ==4){
temp.add(n);
temp.add("****");
}
}
themarklength.clear();
themarklength.addAll(temp);
System.out.println(themarklength);
}
}

Related

why is everything getting removed from my arraylist?

I'm trying to answer this question:
Program the method findIngredients. This method takes in a String called
foodInStock, and an ArrayList of Strings called ingredients. The method should return an
ArrayList of ingredients that were not found in foodInStock.
for example if:
foodInStock = “tomatopotatocornturkeycarrotstuffing”
ingredients = {“potato”, “corn”, “salt”, “chicken”, “turkey”}
returns {“salt”, “chicken”}
I tried writing some code but for some reason everything is getting removed when I use the above example on my program. Where did my program go wrong?
Here's my code:
public static ArrayList<String> findIngredients(String foodInStock, ArrayList<String> ingredients){
ArrayList<String> ingredientsNotFound = new ArrayList<String>();
int i = 0;
for (; i < ingredients.size(); i++) {
for (int x = 0; x < foodInStock.length()-(ingredients.get(i).length())+1; x++) {
if (ingredients.get(i) == foodInStock.substring(x, (x + ingredients.get(i).length()))) {
ingredients.remove(i);
i = 0;
break;
}
}
}
ingredients = ingredientsNotFound;
return ingredientsNotFound;
}
I think there are two main things to cover here.
First, the way to build the final result. You are currently removing items from the original input; a better strategy is to add items to a new list (partially because it's simpler to think about and partially because you generally don't want to modify a list while iterating over it).
You also are, probably accidentally, overwriting your list with an empty list at the end.
Second, the way to determine whether or not the ingredient is in the string input. Rather than looping over the whole string and inspecting substrings, you can instead use the indexOf() method to see whether or not the string includes the current item.
public static ArrayList<String> findIngredients(String foodInStock, ArrayList<String> ingredients) {
ArrayList<String> results = new ArrayList<>();
for (String ingredient : ingredients) {
if (foodInStock.indexOf(ingredient) == -1) {
results.add(ingredient);
}
}
return results;
}
Here we initialize a new list for the results. We then loop over every individual ingredient in the input list, and ask whether or not that ingredient is present in the string input. When it is not (indexOf() returns -1), we add it to the results list. At the end, the results contains every ingredient not found.

Return the updated ArrayList<Characters> after removing the specified element at the index

I am trying to find out if there is a possibility of returning the updated ArrayList after removing the specified element at the index in a single line so that I can pass it on to the recursive function.
Below is a snippet of my code which tries to generate all valid parenthesis combinations given n pairs of "()" brackets.
My concern is in the recursive function call "findAllCombinations" where after some validations I want to remove one character at each recursive call from the arrayList courceSet. However sourceSet.remove(index) returns a character. Instead I want to pass the updated list after removing the character in one line. Is it possible ?
Note : The line below is syntactically wrong and just used for better illustration.
findAllCombinations(sourceSet.remove(index), soFar + singleBracket, singleBracket); .
I did go through the official documentation but did not find any help.
Any help is appreciated, and thanks for your time.
public class GenerateParenthesis {
char singleBracket;
List<String> answerSet = new ArrayList<String>();
char[] repoSet = {'(',')'};
public List<String> generateParenthesis(int n) {
String soFar = "(";
List<Character> sourceSet = new ArrayList<Character>();
for(int i = 0;i<n;i++){
sourceSet.add('(');
sourceSet.add(')');
}
findAllCombinations(sourceSet,soFar,'(');
return answerSet;
}
public void findAllCombinations(List<Character> sourceSet,String soFar,Character toRemove){
if(sourceSet.isEmpty()){
answerSet.add(soFar); // append to a answer set list containing all combinations
return;
}
for(int i = 0;i<2;i++){
singleBracket = repoSet[i];
int index = sourceSet.indexOf(singleBracket);
if(index!=-1) {
findAllCombinations(sourceSet.remove(index), soFar + singleBracket, singleBracket);
}
}
}
public static void main(String args[]){
GenerateParenthesis gp = new GenerateParenthesis();
List<String> ans = new ArrayList<String>();
ans = gp.generateParenthesis(3);
}
}
ArrayList (likely to most List implementations) is a mutable data structure: calling remove you modify the list rather than returning a new list without the removed element.
If you want the latter behavior, the quick and easy way is to do a copy of the list.
// (inside the if...)
// pass the original list to the constructor to make a copy
List<Character> sourceSetCopy = new ArrayList<>(sourceSet);
// modify the copy
sourceSetCopy.remove(index);
// use the modified copy
findAllCombinations(sourceSetCopy, soFar + singleBracket, singleBracket);

Java for-loop never terminates

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());}

what is causing my NoSuchElementException for ArrayList

I know that there are lots of threads on NoSuchElementException in Java here but I still cannot figure out what is going on here
I am trying to come up with a solution for Transitive Dependencies Kata 18 which is posted at http://codekata.pragprog.com/2007/01/kata_eighteen_t.html
dependencies_for method is supposed to take in a char item and compute all dependencies for the item. The exception occurs when I try to add an element to finalDependencies ArrayList
This is the place where my NullPointerException occurs. I have traced all of these data structures and none of them have a Null value. I don't understand what is causing my exception here. Please see my code:
public class Test_Dependencies
{
public static void main(String[] args) {
Dependencies Dep = new Dependencies();
Dep.add_direct('A', "B C");
Dep.add_direct('B', "C D");
Dep.dependencies_for('A');
}
}
public class Dependencies {
HashMap dependenciesList;
public Dependencies()
{
HashMap<Character, ArrayList> dependenciesList = new HashMap<Character, ArrayList>();
}
public void add_direct(char mainItem, String dependentItems)
{
// code that works here
}
public String dependencies_for(char item)
{
ArrayList finalDependencies = new ArrayList<Character>();
Character key = new Character(item);
//get initial dependencies for the item and add them
ArrayList processingDependencies = dependenciesList.get(key);
Iterator itr = processingDependencies.iterator();
while(itr.hasNext())
{
if(finalDependencies.contains(itr.next()) == false && itr.next() != key)
{
// NoSuchElement exception here
finalDependencies.add(itr.next());
// look again at each item in dependenciesList. If it is in the list then add it to processingDependencies
if(dependenciesList.containsKey(itr.next()) && !processingDependencies.contains(itr.next()))
{
processingDependencies.add(itr.next());
}
}
}
// turn finalDependencies into a string
itr = finalDependencies.iterator();
String allDependencies = "";
while(itr.hasNext())
{
allDependencies = allDependencies + " " + itr.next();
}
return allDependencies;
}
}
I am a bit perprlexed because processingDependencies and finalDependencies ArrayLists are not null. And processingDependencies arraylist contains an item
You are calling twice. The first call is "protected" by a matching hasNext Call. The second is not. Save the result of next into a temporary variable and use that, instead of using the value directly, since every call to next will try to advance the iterator first. In the good case, you get an exception. In the bad case, things seem to work, but your program is dealing with the wrong value.
You can't do this:
while(itr.hasNext())
{
if(finalDependencies.contains(itr.next()) == false && itr.next() != key)
{
// NoSuchElement exception here
finalDependencies.add(itr.next());
// stuff removed
}
}
You must verify that iter.hasNext() is true prior to each call of itr.next(). What happens when you reach the last item in itr, but then call itr.next() three times?
Answer: NoSuchElementException. Check out Iterator
The problem is here:
HashMap dependenciesList;
public Dependencies()
{
HashMap<Character, ArrayList> dependenciesList = new HashMap<Character, ArrayList>();
}
You declare a hashmap called dependenciesList. You then try to instantiate that list, but what you actually do is create a local variable named the same thing. They are two separate variables. Then you try to use the one that hasn't been instantiated here:
ArrayList processingDependencies = dependenciesList.get(key);
What you need to do is instantiate the first dependenciesList instead of creating a new one
(I'm not a pro at java, but something like dependenciesList = new HashMap....() instead of HashMap<..> dependenciesList = new HashMap...() )

How to remove strings of length 5 from a set?

I want to remove strings of length 5 from a set, but it keeps outputting the set itself.
public void remove5()
{
Set<String> newSet = new HashSet<String>();
newSet.add("hello");
newSet.add("my");
newSet.add("name");
newSet.add("is");
newSet.add("nonsense");
for(String word: newSet)
{
if(word.length()==5)
{
newSet.remove(word); // Doesn't Help - throws an error Exception in thread "main" java.util.ConcurrentModificationException
}
}
System.out.println(newSet);
}
I want the output to be:
my
name
is
nonsense
(hello was removed because it's 5 characters)
But I get this everytime:
hello
my
name
is
nonsense
Can you please help?
Iterator<String> it= newStr.iterator();
while(it.hasNext()) { // iterate
String word = it.next();
if(word.length() == 5) { // predicate
it.remove(); // remove from set through iterator - action
}
}
For actually modifying your set, you need to do something like this:
Iterator<String> iter = newSet.iterator();
while (iter.hasNext())
if (iter.next().length() == 5)
iter.remove();
Since Strings are immutable, you can't modify the ones that were already added to the set, and anyway, even if you could modify them in-place, replacing them by "" would not remove them from the set.
As other suggested you cannot change a String reason being, Code snippet:
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class TestString {
public void remove5() {
Set<String> newSet = new HashSet<String>();
newSet.add("hello");
newSet.add("my");
newSet.add("name");
newSet.add("is");
newSet.add("nonsense");
for (Iterator<String> iter = newSet.iterator(); iter.hasNext();) {
if (iter.next().length() == 5) {
iter.remove();
}
}
System.out.println(newSet);
}
public static void main(String[] args) {
new TestString().remove5();
}
}
If you iterate over the set and in the loop you remove the object, it will throw you ConcurrentModificationExceptionas HastSet iterator is a fail fast Iterator.
When you find a string of length 5, you need to remove it from the set:
newSet.remove(word);
As it is, you appear to be trying to change word to an empty string, but strings are immutable. What your call actually does is return an empty string.
Strings are immutable, changes made to the String word or any other String will not reflect in the string of Set
add
if(word.length()==5)
{
word.replaceAll(word, "");
newSet.remove(word);
}
you can refer to this function of HashSet
remove(Object o)
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/HashSet.html
Strings are immutable in Java, that means when you call word.replaceAll(word,""), it returns the String "" (which you aren't assigning to anything). The word doesn't change and the Set is still pointing to the old value of word. You need to remove word from the Set itself.
int i = 0;
Set<String> newSet = new HashSet<String>();
newSet.add("hello");
newSet.add("my");
newSet.add("name");
newSet.add("is");
newSet.add("nonsense");
for(String word: newSet)
{
if(word.length()==5)
{
newSet.remove(i);
}
i++;
}

Categories

Resources