• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

Generic ? super ..Question

 
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class EqualsHashcode {

public static void main(String... args){
final int x = 4;


Set<SortOf> set= new HashSet<SortOf>();
SortOf t = new SortOf(2,"abc", (short) x);
SortOf t1 = new SortOf(1,"abc", (short) (x + 4));
set.add(t);
set.add(t1);

ArrayList <? super SortOf> a = new ArrayList<SortOf>();
add(a);
System.out.println(set.size());
}

public static void add(List <? super SortOf> a){
a.add(new Object());
// Compile Time Error
}
}

class SortOf {
String name;

int bal;

String code;

short rate;

SortOf(int bal,String code, short rate){
this.bal = bal;
this.code = code;
this.rate = rate;
}

public int hashcode() {
return (code.length() * bal);
}

public boolean equals(Object o) {
return ((SortOf) o).code.length() * ((SortOf) o).bal
* ((SortOf) o).rate == this.code.length() * this.bal
* this.rate;
}
}

Can anyone explain this behavior? // Compile Time Error why is it coming??
[ September 19, 2007: Message edited by: Yogvinder Singh Ghotra ]
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The List could potentially contain any class that is a superclass of SortOf. So the only thing safe to add to the list is a SortOf object.
 
Ranch Hand
Posts: 278
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
with <? super SortOf>
in mathod argument,
you can add SortOf object only or Null ,not supertypes od SortOf
list.add(new SortOf(..)) as there can be many supertypes..of SortOf.
and yaa ofcourse ,we will get /return only Object.
 
Don't sweat petty things, or pet sweaty things. But cuddle this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic