Java wrapping a collection - java

I need to wrap five classes: linkedlist, treeset, hashset, and two classes I created myself.
The wrapper and my two classes are all implementing the same interface.
this is the wrapper constructor:
private Collection <String> collection;
public CollectionFacadeSet(java.util.Collection<java.lang.String> collection){
this.collection = collection;
}
now, in another class I want to create a 5 cell array that each cell houses a different set.
This line is OK:
static CollectionFacadeSet[] setArray = new CollectionFacadeSet[5];
BUT, when I create a method that fills the cells:
private static void initializieArray(){
setArray[0] = CollectionFacadeSet(HashSet<String>);
}
it throws me an error:
Syntax error on token ">", Expression expected after this token
How to initiate each cell with a different set type?

The expression
setArray[0] = CollectionFacadeSet(HashSet<String>);
is invalid. You would need something like
setArray[0] = new CollectionFacadeSet(new HashSet<String>());
instead.

static CollectionFacadeSet[] setArray = new CollectionFacadeSet[5];
Array will store the objects of CollectionFacadeSet so use new
setArray[0] = new CollectionFacadeSet(new HashSet<String>());

Related

ArrayList[] needs unchecked conversion to conform to ArrayList<String>[] [duplicate]

I am trying do something like this:-
public static ArrayList<myObject>[] a = new ArrayList<myObject>[2];
myObject is a class. I am getting this error:- Generic array creation (arrow is pointing to new.)
You can't have arrays of generic classes. Java simply doesn't support it.
You should consider using a collection instead of an array. For instance,
public static ArrayList<List<MyObject>> a = new ArrayList<List<MyObject>();
Another "workaround" is to create an auxilliary class like this
class MyObjectArrayList extends ArrayList<MyObject> { }
and then create an array of MyObjectArrayList.
Here is a good article on why this is not allowed in the language. The article gives the following example of what could happen if it was allowed:
List<String>[] lsa = new List<String>[10]; // illegal
Object[] oa = lsa; // OK because List<String> is a subtype of Object
List<Integer> li = new ArrayList<Integer>();
li.add(new Integer(3));
oa[0] = li;
String s = lsa[0].get(0);
There is a easier way to create generic arrays than using List.
First, let
public static ArrayList<myObject>[] a = new ArrayList[2];
Then initialize
for(int i = 0; i < a.length; i++) {
a[i] = new ArrayList<myObject>();
}
You can do
public static ArrayList<myObject>[] a = (ArrayList<myObject>[])new ArrayList<?>[2];
or
public static ArrayList<myObject>[] a = (ArrayList<myObject>[])new ArrayList[2];
(The former is probably better.) Both will cause unchecked warnings, which you can pretty much ignore or suppress by using: #SuppressWarnings("unchecked")
if you are trying to declare an arraylist of your generic class you can try:
public static ArrayList<MyObject> a = new ArrayList<MyObject>();
this will give you an arraylist of myobject (size 10), or if u only need an arraylist of size 2 you can do:
public static ArrayList<MyObject> a = new ArrayList<MyObject>(2);
or you may be trying to make an arraylist of arraylists:
public static ArrayList<ArrayList<MyObject>> a = new ArrayList<ArrayList<MyObject>>();
although im not sure if the last this i said is correct...
It seems to me that you use the wrong type of parenthesis. The reason why you can't define an array of generic is type erasure.
Plus, declaration of you variable "a" is fragile, it should look this way:
List<myObject>[] a;
Do not use a concrete class when you can use an interface.

Cannot find symbol error sorting Collection with Collections.sort()

Edit: Solved! Thanks everybody.
I'm trying to sort a collection in Java using the Comparator with no luck. Here's my code:
public class Collections_Exercise {
public void runExercise(){
String[] emailArray = {"andy#test.com","paul#test.com","cindy#test.com", "robert#test.com", "bill#test.com", "andy#test.com", "cindy#test.com"};
Collection<String>emails = new ArrayList<String>(Arrays.asList(emailArray));
processEmails(emails);
// 5. Call processEmails with a sorted list of emails with duplicate email addresses removed
System.out.println("Sorted list of emails with no dups!");
class alphabeticalComparator implements Comparator<String>
{
#Override
public int compare(String email1, String email2)
{
int result = email1.toString().compareTo(email2.toString());
return result;
}
}
Collections.sort(emails, new alphabeticalComparator()); //Doesn't work, can't find collections.sort() symbol
processEmails(emails);
private void processEmails(Collection<String> emails)
{
for( String s : emails)
System.out.println(s);
}
public static void main(String [] args)
{
new Collections_Exercise().runExercise();
}
}
No matter what I try I can't get Collections.sort() to work. Any tips?
Edit: This is the error that terminal is giving me:
Collections_Exercise.java:58: cannot find symbol
symbol : method sort(java.util.Collection<java.lang.String>,alphabeticalComparator)
location: class java.util.Collections
Collections.sort(emails, new alphabeticalComparator());
Collections#sort takes a List, not a Collection.
List<String> emails = new ArrayList<String>(Arrays.asList(emailArray));
The reason for this is that there are some classes implementing Collection that cannot be reordered arbitrarily. Some have a storage mechanism that depends on elements being placed strategically (such as HashSet) and others have a predetermined sorted order (such as TreeSet).
Collection says this about it:
The root interface in the collection hierarchy. ... Some are ordered and others unordered. The JDK [only] provides implementations of more specific subinterfaces like Set and List. This interface is typically used ... where maximum generality is desired.
Hence why you only see Collection as a parameter in places like conversion constructors (which the tutorial calls a convention) and the family of xxxAll methods.
In Java a container of type Collection, by definition, has no order and can therefore not be sorted. Only its child List can be ordered.
Consequently the Collections#sort method expects an object of type List as first argument, but you are providing a Collection.
Change
Collection<String> emails = new ArrayList<String>(Arrays.asList(emailArray));
into
List<String> emails = ...
You miss a
}
after processEmails(emails);
and you have to change from
Collection<String>
to
List<String>
Try replacing:
Original
Collection<String>emails = new ArrayList<String>(Arrays.asList(emailArray));
New
ListString>emails = new ArrayList<String>(Arrays.asList(emailArray));
As per Java API Collections.sort accept List.
List<String> emails = Arrays.asList(emailArray);
Collections.sort(emails, new alphabeticalComparator());
Collections.sort() expects a List not a Collection, see here. Thus, instead of
Collection<String>emails = new ArrayList<String>(Arrays.asList(emailArray));
it should be
final List<String>emails = Arrays.asList(emailArray);

Confused about arrayList

I got this line of code when I asked the teacher for some help, but I get a redline below the last part. What could be wrong? The error message: "The type of the expression must be an array type but it resolved to ArrayList" I don't understand that, please help me to understand.
ArrayList<Point>[] touchPoints = new ArrayList<Point>()[2];
I want to have two lists to save Points. I guess I call each list like touchPoints[0]; and touchPoints[1]; !?
EDIT:
I guess I can keep it simple and just use two different List like this!?:
points1 = new ArrayList<Point>();
points2 = new ArrayList<Point>();
You have created an array of ArrayLists. This demo shows how they are used together
import java.util.ArrayList;
public class ArraysAndLists {
public static void main(String[] args) {
ArrayList<String>[] touchPoints = new ArrayList[2];
// Adding values
touchPoints[0] = new ArrayList<String>();
touchPoints[0].add("one string in the first ArrayList");
touchPoints[0].add("another string in the first ArrayList");
touchPoints[1] = new ArrayList<String>();
touchPoints[1].add("one string in the second ArrayList");
touchPoints[1].add("another string in the second ArrayList");
// touchPoints[2].add("This will give out of bounds, the array only holds two lists");
// Reading values
System.out.println(touchPoints[0].get(0)); // returns "one string in the first ArrayList"
System.out.println(touchPoints[1].get(1)); // returns "another string in the second ArrayList"
}
}
check out this Question
The component type of an array object may not be a type variable or a parameterized type, unless it is an (unbounded) wildcard type.You can declare array types whose element type is a type variable or a parameterized type, but not array objects.
You are mixing two things:
Constructing a plain array
Constructing an ArrayList
Constructing an array
A plain array is very low level. Does not have methods, and its length is fixed after you create it.
MyType[] anArray = new MyType[10];
Constructing an ArrayList
ArrayList is just an implementation of a type of Collection
Collection<MyItemType> aCollection = new ArrayList<MyItemType>();
What to do in your case?
You want a plain array of collections (which implementation is ArrayList). So:
// Create the array, use the interface in case you need to change the implementation later on
Collection<Point>[] touchPoints = (Collection<Point>) new Collection[2];
// Create each collection within that array, using the ArrayList implementation
touchPoints[0] = new ArrayList<Point>();
touchPoints[1] = new ArrayList<Point>();
How to do it better?
Try to think about why you need a plain array:
if it's just 2 elements, and always fixed, simply create two member variables.
if number can vary, just create a Collection of Collections (Collection>)
Edit given your use case:
Just create a class to hold your user input:
class UserInput {
public UserInput() {
user1TouchPoints = new ArrayList<Point>();
user2TouchPoints = new ArrayList<Point>();
}
// Add accessors and all
private Collection<Point> user1TouchPoints;
private Collection<Point> user2TouchPoints;
}
If you plan to have more players, simply use a map
class UserInput {
public UserInput() {
usersTouchPoints = new HashMap<Integer, Collection<Point>>();
}
public Collection<Point> getUserTouchPoints(Integer userId) {
return usersTouchPoints.get(userId);
}
public void addUserTouchPoints(Integer userId, Collection<Point> input) {
Collection<Point> points = usersTouchPoints.get(userId);
if (points==null) {
points = new ArrayList<Point>();
userTouchPoints.put(userId, points);
}
points.addAll(input);
}
// Maps a user ID (or index) to its touch points
// If you are using Android, use SparseArray instead of Map, this is more efficient
private Map<Integer, Collection<Point>> usersTouchPoints;
}

java generics wildcard compiling error (generic of generic)

Hello I have a compiling problem with this peace of code. How can I perform a safe add to data variable?
import java.util.*;
public class Foo
{
private TreeSet<? extends Collection<String>> data;
public Foo()
{
data = new TreeSet<ArrayList<String>>();
data.add("Goofy"); //this action generates a compile error
}
}
You're trying to add a String to a TreeSet of ArrayLists of Strings. You would need to add an ArrayList. Probably
ArrayList<String> list = new ArrayList<>();
list.add("Goofy");
data.add(list);
That is, assuming you're not using an overcomplicated design, which you very much probably are.
data is a collection of ArrayList and you are trying to add a String
You need to add the String to an array list first
ArrayList<String> list = new ArrayList<String>();
list.add("Goofy");
data.add(list);
or change data to be a TreeSet of Strings
private TreeSet<String> data;
data = new TreeSet<String>();
data.add("Goofy");

Generic array creation error

I am trying do something like this:-
public static ArrayList<myObject>[] a = new ArrayList<myObject>[2];
myObject is a class. I am getting this error:- Generic array creation (arrow is pointing to new.)
You can't have arrays of generic classes. Java simply doesn't support it.
You should consider using a collection instead of an array. For instance,
public static ArrayList<List<MyObject>> a = new ArrayList<List<MyObject>();
Another "workaround" is to create an auxilliary class like this
class MyObjectArrayList extends ArrayList<MyObject> { }
and then create an array of MyObjectArrayList.
Here is a good article on why this is not allowed in the language. The article gives the following example of what could happen if it was allowed:
List<String>[] lsa = new List<String>[10]; // illegal
Object[] oa = lsa; // OK because List<String> is a subtype of Object
List<Integer> li = new ArrayList<Integer>();
li.add(new Integer(3));
oa[0] = li;
String s = lsa[0].get(0);
There is a easier way to create generic arrays than using List.
First, let
public static ArrayList<myObject>[] a = new ArrayList[2];
Then initialize
for(int i = 0; i < a.length; i++) {
a[i] = new ArrayList<myObject>();
}
You can do
public static ArrayList<myObject>[] a = (ArrayList<myObject>[])new ArrayList<?>[2];
or
public static ArrayList<myObject>[] a = (ArrayList<myObject>[])new ArrayList[2];
(The former is probably better.) Both will cause unchecked warnings, which you can pretty much ignore or suppress by using: #SuppressWarnings("unchecked")
if you are trying to declare an arraylist of your generic class you can try:
public static ArrayList<MyObject> a = new ArrayList<MyObject>();
this will give you an arraylist of myobject (size 10), or if u only need an arraylist of size 2 you can do:
public static ArrayList<MyObject> a = new ArrayList<MyObject>(2);
or you may be trying to make an arraylist of arraylists:
public static ArrayList<ArrayList<MyObject>> a = new ArrayList<ArrayList<MyObject>>();
although im not sure if the last this i said is correct...
It seems to me that you use the wrong type of parenthesis. The reason why you can't define an array of generic is type erasure.
Plus, declaration of you variable "a" is fragile, it should look this way:
List<myObject>[] a;
Do not use a concrete class when you can use an interface.

Categories