Write JAVA statements from the client perspective to accomplish the following ta
ID: 667398 • Letter: W
Question
Write JAVA statements from the client perspective to accomplish the following task.
Create an array of distinct Strings contained in a bag
The bag should be unchanged when your code is complete
For example, if the BagInterface<String> object myWords initially contained
hi, hello, hi, bye, hi, bye
Then after your method completes, myWords will still contain:
hi, hello, hi, bye, hi, bye
A new array that you create will contain:
hi, hello, bye (in any order)
We can use a second, initially empty BagInterface<String> object, called tempBag, if it helps.
Explanation / Answer
import java.io.*;
import java.util.*;
class main{
public static void distinct(ArrayList<String> ar){
ArrayList<String> temp = new ArrayList<String>();
for (int i = 0; i < ar.size(); i++){
String s = ar.get(i);
if (temp.contains(s) == false)
temp.add(s);
}
System.out.print("Original bag contains : ");
for(int i = 0; i < ar.size(); i++)
System.out.print(ar.get(i)+" ");
System.out.println(); System.out.println(); System.out.println();
System.out.print("bag contains distinct items : ");
for(int i = 0; i < temp.size(); i++)
System.out.print(temp.get(i)+" ");
System.out.println(); System.out.println(); System.out.println();
}
public static void main(String[] args){
ArrayList<String> bag = new ArrayList<String>();
bag.add("hi"); bag.add("hello"); bag.add("bye"); bag.add("hi"); bag.add("bye"); bag.add("hello");
distinct(bag);
}
}
for output ----- http://ideone.com/BXzrcS
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.