Converting Collections to Strings, getting invalid method declaration - java

I'm working on an assignment and I feel super close! But I just don't understand the last error message I'm getting and was wondering if you could help me understand it so I avoid it in the future.
The assignment started off with an example code:
import java.util.*;
public class Proj09{
public static void main(String args[]){
new Proj09Runner().getCollection();
}
}
class Proj09Runner{
public void getCollection(){
Collection collection = new TreeSet();
Populator.fillIt(collection);
Iterator iter = collection.iterator();
while(iter.hasNext()){
System.out.print(iter.next());
}
System.out.println();
}
}
class Populator{
public static void fillIt(Collection collection){
collection.add("Able");
collection.add("Baker");
collection.add("aBle");
collection.add("Charley");
collection.add("Baker");
}
}
Output: Able Baker aBle Charley Baker
And our job is to change that code so that it fits a different main that I'm not able to edit:
import java.util.*;
public class Proj09{
public static void main(String args[]){
Proj09Runner runner = new Proj09Runner();
Collection <String> collection = runner.getCollection();
collection.add("Able");
collection.add("Baker");
collection.add("aBle");
collection.add("Charley");
collection.add("Baker");
Iterator <String> iter = collection.iterator();
while(iter.hasNext()){
System.out.print(iter.next() + " ");
}
System.out.println();
}
}
So far, I've been playing with the Proj09Runner class:
class Proj09Runner extends Proj09{
public void getCollection(){
System.out.println("My Name.");
System.out.println();
}
}
Small change to the output, I'm supposed to add my name.
Desired output:
My Name
Able Baker aBle Charley Baker
But I keep getting different errors that go back to the line Collection <String> collection = runner.getCollection(); in the main I'm not supposed to change. I'll get called out on void's not being able to be converted to Collection <String> or "invalid method declaration; return type required."
Could y'all help me figure out why I'm getting those messages and what they mean so that I can avoid them in the future?
Thanks, I really do appreciate it.

This for sure needs improvement :
Collection <String> collection = runner.getCollection();
this does not return a Collection<String>, note your method returns nothing.
public void getCollection(){
Either your method return type and definition changes something like :
public Collection<String> getCollection(){ //followed by corresponding definition
Or you can simply use
Collection <String> collection = new HashSet() ; //whatever your collection pertain to

public Collection<String> getCollection(){
Collection collection = new TreeSet();
Populator.fillIt(collection);
Iterator iter = collection.iterator();
while(iter.hasNext()){
System.out.print(iter.next());
}
System.out.println();
return collection;
}
your getCollection method is returning nothing. it should return a collection

I've been trying this and it seems to be a good direction. Keeping the main:
import java.util.*;
public class Proj09{
public static void main(String args[]){
Proj09Runner runner = new Proj09Runner();
Collection <String> collection = runner.getCollection();
collection.add("Able");
collection.add("Baker");
collection.add("aBle");
collection.add("Charley");
collection.add("Baker");
Iterator <String> iter = collection.iterator();
while(iter.hasNext()){
System.out.print(iter.next() + " ");
}
System.out.println();
}
}
I've now got:
class Proj09Runner{
public Collection<String> getCollection(){
return "Hailey";
}
}
I didn't want to reiterate what was already in the main as it seemed unnecessary. Returning the string "Hailey" addressed the old error, but a new one has popped up.
error: cannot find symbol
public Collection<String> getCollection(){
^
symbol: class Collection
location: class Proj09Runner
Do you know what that type of error indicates?
Our last unit was about inheritance, and I played with "Proj09Runner extends Proj09{" but it didn't seem to have an effect.

I wanted to go ahead and share the answer:
import java.util.*;
class Proj09Runner{
public Collection <String> getCollection(){
System.out.println("Name.");
Collection collection = new ArrayList();
return collection;
}
}
I couldn't go with TreeSet because it doesn't accept duplicates and so would only print "Baker" once, so I went with ArrayList instead.
Thanks a bunch for the feedback!

Related

Adding a array list to arraylist

import java.util.*;
class test2{
static void fun(int i,int arr[],List<Integer> l,int n,List<List<Integer>> res){
if(i==n){
if(l.size()!=0){
//System.out.println(l.size());
res.add((l));
//System.out.println(res);
}
//System.out.println(l);
return;
}
l.add(arr[i]);
fun(i+1,arr,l,n,res);
//System.out.println(l);
l.remove(l.size()-1);
//System.out.println(l);
fun(i+1,arr,l,n,res);
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
List<Integer> l=new ArrayList<>();
List<List<Integer>> res=new ArrayList<>();
fun(0,arr,l,n,res);
System.out.println(res);
}
}
in fun function while i am adding a List to other List it is adding empty list i could find the reason can somebody help me this program is about finding the different combinations of given array
You can use res.add((new ArrayList<>(l)) instead of res.add((l)).
Why should use (new ArrayList<>(existing_list))?
When you update any primitive value then put in a list you can update again that primivite value. That does not change the value in list. But an object does not work like that. Well we can say it causes kind of pointer. When you update an object then it updates the values in its address. Let me show you a short example.
public class MyObject {
private List<String> list = new ArrayList<>();
public MyObject() {
list.add("added in Constructor");
}
public List getList() {
return list;
}
}
public static void main(String[] args) {
MyObject myObject = new MyObject();
System.out.println("--> Object list (Before added anything in main) : ");
myObject.getList().forEach(System.out::println);
List list = myObject.getList();
list.add("added in Main");
System.out.println("--> local list : ");
list.forEach(System.out::println);
System.out.println("--> Object list (After added a value in main) : ");
myObject.getList().forEach(System.out::println);
}
And the ouput is :
--> Object list (Before added anything in main) :
added in Constructor
--> local list :
added in Constructor
added in Main
--> Object list (After added a value in main) :
added in Constructor
added in Main
I did not set up a new Arraylist or create new one but my private list in MyObject is updated even if I just do changes in main function.
But instead of list If I returned new Array<>(list) then even if I update the list in main, my list would never change. Because I return another address with new Array<>(list). So you should add your list with another addres. I mean another Arraylist. So you can use res.add((new ArrayList<>(l)) instead of res.add((l)).

Illegal state Exception Occurring with ArrayList [duplicate]

This question already has an answer here:
IllegalStateException when removing an object with iterator
(1 answer)
Closed 5 years ago.
I was trying to run the below code in my system and encountered Illegal State Exception while doing so.
import java.util.*;
public class ArraylistExample2
{
public static void main(String args[])throws Exception
{
ArrayList <String> al = new ArrayList<String>();
al.add("A");al.add("B");al.add("C");
Iterator <String> i = al.iterator();
while(i.hasNext())
{
if(al.contains("B"))
{
i.remove();
System.out.println(" Element B removed");
}
System.out.println(i.next());
}
}
}
Can someone please explain what is wrong with the code here or what method has been illegally called giving rise to this exception ? Below is the stack Trace:
java.lang.IllegalStateException
at java.util.ArrayList$Itr.remove(ArrayList.java:864)
at collectionsExamples.ArraylistExample2.main(ArraylistExample2.java:17)
The cursor hasn't moved to an element yet. You just checked whether there is an element or not.
You are removing an element from iterator before actually starting the iteration. Hence there is no current element in the iterator to remove.
First move the cursor for next element and then try to remove it if the criteria matched.
So, the modified code looks like
while(i.hasNext())
{
Strng s = i.next(); // note this
if(al.contains("B"))
{
i.remove();
System.out.println(" Element B removed");
}
System.out.println(s);
}
Here is the correct implementation, you need not to check if(al.contains("B")) rather check if the elemnent value is B
import java.util.*;
public class ArraylistExample2
{
public static void main(String args[])throws Exception
{
ArrayList <String> al = new ArrayList<String>();
al.add("A");al.add("B");al.add("C");
Iterator <String> i = al.iterator();
while(i.hasNext())
{
String element=i.next();
if("B".equals(element))
{
i.remove();
System.out.println(" Element B removed");
}
}
}
}

Add ArrayList to another ArrayList in java with Iterator

I have a huge problem with my code:
public class BookStore
{
private ArrayList<Book> books;
}
/**
* This method takes the author's name as a String parameter and returns an
* arraylist of all the books written by that author. It uses a while loop
* and an iterator, locates the books written by that author (case-insensitive)
* and adds them to another arraylist.
*/
public ArrayList<Book> getBooksByAuthor(String authorName){
ArrayList<Book> getBooksByAuthor = new ArrayList<Book>();
Iterator<Book> aBook = books.iterator();
while(aBook.hasNext()){
Book aBookd = aBook.next();
if (authorName.equalsIgnoreCase(aBookd.getAuthor())){
books.add(getAuthor());
books.addAll(getBooksByAuthor);
}
}
return getBooksByAuthor.size();
}
Those 3 lines
books.add(getAuthor());
books.addAll(getBooksByAuthor); and the
return getBooksByAuthor.size();
I'm pretty sure that they are completely wrong. I tried different ways to do it ,but it didn't work. I really don't understand how to do that. Could someone help me?. Thank you for your time!
I'm fairly certain you wanted to add the book(s) with matching author's name to a new List. Something with an implicit iterator using a for-each loop
List<Book> al = new ArrayList<>();
for (Book book : books) {
if (authorName.equalsIgnoreCase(book.getAuthor())) {
al.add(book);
}
}
return al;
or using an explicit Iterator like
List<Book> al = new ArrayList<>();
Iterator<Book> iter = books.iterator();
while (iter.hasNext()) {
Book book = iter.next();
if (authorName.equalsIgnoreCase(book.getAuthor())) {
al.add(book);
}
}
return al;
is there any specific need for the iterator and a while-loop instead of a foreach loop?
what (i think) you'd like to achive is in normal language is: we have an empty collection/list as result. for each book in the list of books, check if the author has an equal name to the given name - if the names are equal, we add the book to the resulting collection/list.
that in code looks like:
public ArrayList<String> getBooksByAuthor(String authorName) {
ArrayList<Book> result = new ArrayList<Book>();
for (Book aBook : books) { //[for each notation in java ][1]
if (authorName.equals(aBook.getAuthor())) {
result.add(aBook);
}
}
return result;
}
if you'd like to use a while loop, read up the foreach/while loop conversion in the this link.
in addition and as mentioned in the comments, your code has some semantic and syntactic errors:
your return type is wrong (int instead of ArrayList)
your class definition closing brace ends before your method definition
you add the author object (probably a string) to your books-collection
you never add any book to your resulting collection
you try to addAll objects of your (empty) collection getBooksByAuthor to your books, instead of adding some/single books to your getBooksByAuthor collection
[1] http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html

Printing the values in an intList

I have an array 'store' that stores a number of LinkedLists called intList.
How do I print the values held in each list? I tried to print it as follows:
system.out.println(store[i].toString);
but get the following in return:
intList#16ad9f5d
or something similar.
Any help would be great, thanks
A java.util.LinkedList has a nice toString() method (so no need to write it yourself, reinvent the wheel etc.), so most probably you don't call it at all. Seems like you're doing something like toArray().toString(), or maybe store.toString().
Extend LinkedList and implement toString().
Public class YourLinkedList<String> extends LinkedList<String> {
//You code goes here or blank
#Override
public String toString() {
return Arrays.toString(this.toArray());
}
}
You will get output as : [fdf, fdfdf, fdfdf]
for(List l : arr)
{
Iterator it = l.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
Something like this might work...
I think This code helps to you.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class Test {
public static void main(String args[])
{
LinkedList<Integer> l1=new LinkedList<Integer>();
l1.add(1);
l1.add(2);
LinkedList<Integer> l2=new LinkedList<Integer>();
l2.add(3);
l2.add(4);
LinkedList<LinkedList<Integer>> sort=new LinkedList<LinkedList<Integer>>();
sort.add(l1);
sort.add(l2);
for(List l : sort)
{
Iterator it = l.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
}
Use iterator as this :
Iterator iter = yourList.iterator();
while(iter.hasNext()) {
System.out.println(iter.next());
}

Iterating a Collection more than once

I am having trouble using Iterator in java.
it=myHash.iterator();
while (it.hasNext())
if (it.next() satisfying something)
do something
while (it.hasNext())
if (it.next() satisfying something)
it.remove();
I am trying to iterate hashset twice, and the first loop making it.hasNext() return false. How to i resolve this?
I tried even adding the edit as you guys suggested, still not working...
You're reusing the same iterator - and that's been invalidated by adding new items to the set.
You should call iterator() again on the set:
it = set.iterator();
You can't reset the existing iterator
EDIT: Here's some sample code which shows this working:
import java.util.*;
public class Test {
public static void main(String[] args) {
Set<String> set = new HashSet<String>();
set.add("food");
set.add("bad");
set.add("hungry");
set.add("neighbour");
Iterator<String> it = set.iterator();
// Remove any string longer than 4
while (it.hasNext())
{
if (it.next().length() > 4)
{
it.remove();
}
}
set.add("new long text");
set.add("x");
// Remove any string shorter than 4
it = set.iterator();
while (it.hasNext())
{
if (it.next().length() < 4)
{
it.remove();
}
}
// Dump the results
for (String x : set)
{
System.out.println(x);
}
}
}
This gives the results "new long text" and "food".
Ideally, what you are looking for is a reset operation on an Iterator. Iterators are meant to be unidirectional and one-time use, as such they don't have support for reset in Java.
You can either get hold of a new Iterator instance or use ListIterator interface which allows you to look backwards using previous().
Edit:
You are using remove() on the iterator which is also removing elements from the original set. In such a case you should consider making a copy of the set since you want to iterate over the elements all over again:
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
public class IteratorSnippet {
public static void main(String[] args) {
final HashSet<Integer> myHash = new HashSet<Integer>();
myHash.addAll(Arrays.asList(1, 2, 3, 4, 5));
// make copy before using iterator with remove
final HashSet<Integer> myHash2 = new HashSet<Integer>(myHash);
Iterator<Integer> it = myHash.iterator();
System.out.println("First go...");
while (it.hasNext()) {
System.out.println(it.next());
it.remove();
}
it = myHash2.iterator();
System.out.println("Second go...");
while (it.hasNext()) {
System.out.println(it.next());
}
}
}

Categories

Resources