I tried to create an interface ISortableStack using <E extends comparable <E>> but I can't move forward. What does the following do?
<E extends Comparable<E>>
I've tried this, but it doesn't help.
<E extends Comparable<E>> means that E must be a type that knows how to compare to itself, hence, the recursive type definition.
public class Comparables {
static class User implements Comparable<User> {
#Override
public int compareTo(User user) {
return 0;
}
}
/**
* This class cannot be used with Collections.sort because an
* UncomparableUser is not comparable with itself. However, notice
* that you get no compiler error just for implementing
* Comparable<String>.
*/
static class UncomparableUser implements Comparable<String> {
#Override
public int compareTo(String user) {
return 0;
}
}
public static void main(String[] args) {
List<User> users = Arrays.asList(new User());
// Using this would cause a compiler error
// List<UncomparableUser> users = Arrays.asList(new UncomparableUser());
Collections.sort(users);
}
}
If you're asking what does this mean:
<E extends Comparable<E>>
It means that the class 'E' passed in must implement the Comparable interface.
The < and > characters are part of the "generic" syntax. The standard library is choke full of "generic" interfaces; take a look at the Set interface for an example.
Related
my code is as below, and I got the error message Bound Mismatch Error: The type String is not a valid substitute for the bounded parameter <K extends myComparable<K>> of the type myInterface<K,V>:
interface myComparable<T> {
public int compareTo(T o);
}
interface myInterface<K extends myComparable<K>, V> {
}
public class myClass implements myInterface<String,String>{
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
However, if I changed K extends myComparable<K> to K extends Comparable<K> (without changing the first line; i.e. to use Comparable instead of myComparable), the error will be solved.
Why? And how can I use my own myComparable?
I finally got a solution (i.e. to use myString instead of String):
interface myComparable<T> {
public int compareTo(T o);
}
interface myInterface<K extends myComparable<K>, V> {
}
class myString implements myComparable<myString>{
#Override
public int compareTo(myString o) {
return 0;
}
}
public class myClass implements myInterface<myString,myString>{
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
When you write implements myInterface<String, String>, you're 'binding' the K type variable to String and the V type variable to String.
The declaration of the K type variable in particular has a bound on it: You've declared it as myInterface<K extends myComparable<K>, V> which means that any bound you pick for K must at least 'fit' this restriction.
And it doesn't, which is why the compiler won't let you.
The java.lang.String class actually implements Comparable<String> - it's right there in the javadoc as well as the source if you care to look; you can also just cast it:
Comparable<String> test = "hello"; // this compiles and runs fine.
The reason is that string was written by sun/oracle as: public final class String implements Comparable<String>.
It was not written with implements myComparable<String>.
It is not possible to make java.lang.String implement your interface.
That is not how interfaces work; java is nominally and not structurally typed: You can't decree that all Strings are myComparables, just because they so happen to have a compareTo method.
Imagine it worked that way and I wrote this class:
public class Gun {
public void shoot(Person person) { ... }
}
quite a dangerous class!
Let's say it worked the way you appear things are. Then I could do:
public interface Camera {
public void shoot(Person p);
}
Camera c = new Gun();
c.shoot(somebody);
and good grief, now we have an extremely dangerous situation going on. Fortunately, java does not work this way; A Gun is not a Camera. Eventhough it so happens to have all the methods that the Camera interface declared.
You can make your own types that implement your own interfaces, of course. That's no problem. However, in general, it doesn't seem useful to make an interface named myComparable.
I am facing some difficulty to understand an expression in java generics.
Please help on this:
public interface Inter {
<T extends Enum<T> & FunctionalInterface> String getString();
}
The code you have given is legal, but useless.
It is useless for two reasons:
You have defined a generic type, T, as part of the method declaration that must implement the Enum<T> interface as well as the FunctionalInterface interface. However you haven't then used that type anywhere in the method's signature (i.e. arguments or return type) so it is effectively ignored.
Having an interface implement 'FunctionalInterface' is possible, but certainly not it's intended use. It is designed to be an annotation to an interface, not an interface itself.
You could make this combination work:
public interface Inter {
<T extends Enum<T> & FunctionalInterface> String getString(T value);
}
static class InterImpl implements Inter {
#Override
public <T extends Enum<T> & FunctionalInterface> String getString(T value) {
return value.name();
}
}
enum EnumImpl implements FunctionalInterface {
A, B, C;
#Override
public Class<? extends Annotation> annotationType() {
return null;
}
}
public static void main(String[] args) {
InterImpl impl = new InterImpl();
System.out.println(impl.getString(EnumImpl.B));
}
You'll see that the EnumImpl enumeration implemements Enum and FunctionalInterface so it can be used as an argument to getString.
So that's an explanation but, frankly, I can't think of any useful use case for such a piece of code.
I have a little problem connected with interfaces, classes and generics in Java.
First of all, I have an interface which is meant to represent the idea of Priority Queue:
public interface PriorityQueue<T> {
// insert object o of class T into priority queue with appropriate element
public void insert(T o);
// remove an element with the highest priority
public T remove();
}
As we know we can implement a priority queue by heap or list. Here's my class of heap:
public class Heap <T implements Comparable> implements PriorityQueue<T>
I want to have an ArrayList which will have elements of type T. I want my heap to be prepared for all types which are comparable (classes which implement interface Comparable). T could be a String, Double, Integer or just my own type (then I know that I have to write a compareTo method...).
How can I do that? I have a lot of errors in my NetBeans...
Instead of
public class Heap <T implements Comparable> implements PriorityQueue<T>
write:
public class Heap<T extends Comparable> implements PriorityQueue<T>
It works (Of course implement inherited methods). See here for more information.
You're pretty close. Try: public class Heap<T extends Comparable>...
This is one of the many weird and, IMO, unfortunate things about Java Generics. You never use the implements keyword inside of the < >, only extends. Here's a JUnit test showing it in action:
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
public class CalcIEProjectTreeTest {
public static interface Priority<T> {
public void insert(T item);
public T remove();
}
public static class Heap<T extends Comparable> implements Priority<T> {
private List<T> storage = new ArrayList<T>();
public void insert(T item){
storage.add(item);
}
public T remove() {
return storage.remove(0);
}
}
#Test
public void testStuff() throws Exception {
Heap h = new Heap<String>();
h.insert("testString");
assertEquals("testString", h.remove());
}
}
never mind the bogus formatting.
I am new to java. I am just trying to pass Comparable<String> into a method parameter of generic type <E extends Comparable<E>> . I believe the meaning of <E extends Comparable<E>> is any object that extends Comparable. Please let me know how to pass Comparable<String> or any object that extends Comparable<String> and has an other object in it.
Compiler is giving me error The inferred type Compare<String> is not a valid substitute for the bounded parameter <E extends Comparable<E>>
Code:
public class Compare<T> implements Comparable<T>{
public int compareTo(T o) {
return 0; // Not worried about logic
}
}
class CompareTest{
public <E extends Comparable<E>>void testGeneric(E e){
System.out.println("Executed");
}
public static void main(String args[]){
Compare<String> compare = new Compare<String>();
CompareTest test = new CompareTest();
test.testGeneric(compare);
//The inferred type Compare<String> is not a valid substitute for the bounded
//parameter <E extends Comparable<E>>
}
}
E extends Comparable<E> means: a type E that is able to compare to other objects of the same type E.
But your Compare type doesn't qualify. It can't compare with another Compare. A Compare<T> can only compare itself to a T, and not to a Compare<T>, since it's declared as
public class Compare<T> implements Comparable<T>
It's quite hard to understand what you want to achieve with this Compare type.
Your method
public <E extends Comparable<E>> void testGeneric(E e){
expects a type E that is a sub type of Comparable<E>. But you are passing it a Compare<String> which is not a sub type of <Comparable<Compare<String>>, but a sub type of Comparable<String>.
You'll have to clarify what you are trying to do if you need more help.
The error in my IDE says:
Inferred type 'Compare<java.lang.String>' for type parameter 'E' is not within its bound;
should implement 'java.lang.Comparable<Compare<java.lang.String>>'
It seems that E is inferred as Compare<String> instead of String. To get E to be String, try this:
public <E extends Comparable<E>> void testGeneric(Comparable<E> e){
To define a class as being comparable, the generic parameter to Comparable must be the class itself:
public class MyComparable implements Comparable<MyComparable> {
public int compareTo(MyComparable o) {
return 0;
}
}
Applying that to your class, you get the following code (which compiles):
public static class Compare<T> implements Comparable<Compare<T>> {
public int compareTo(Compare<T> o) {
return 0; // Not worried about logic
}
}
class CompareTest {
public <E extends Comparable<E>> void testGeneric(E e) {
System.out.println("Executed");
}
}
public static void main(String[] args) {
Compare<String> compare = new Compare<String>();
CompareTest test = new CompareTest();
test.testGeneric(compare);
}
I want to have an interface A parameterised by T A<T>, and also want every class that implements it to also implement Comparable (with T and its subtypes). It would seem natural to write interface A<T> extends Comparable<? extends T>, but that doesn't work. How should I do it then?
When Comparable<? extends T> appears it means you have an instance of Comparable that can be compared to one (unknown) subtype of T, not that it can be compared to any subtype of T.
But you don't need that, because a Comparable<T> can compare itself to any subtype of T anyway, e.g. a Comparable<Number> can compare itself to a Comparable<Double>.
So try:
interface A<T> extends Comparable<T> {
// ...
}
or
interface A<T extends Comparable<T>> extends Comparable<A<T>> {
// ...
}
depending on whether you need to be able to compare instances of T in order to implement your compareTo method.
If you use comparable you do not need to specify the possibility for subtypes in the compare function, it is by nature possible to pass in any subtype of an object X into a method that declared a parameter of class X. See the code below for more information.
public interface Test<T> extends Comparable<T> {
}
class TestImpl implements Test<Number> {
#Override
public int compareTo(final Number other) {
return other.intValue() - 128;
}
}
class TestMain {
public static void main(final String[] args) {
TestImpl testImpl = new TestImpl();
testImpl.compareTo(Integer.MIN_VALUE);
}
}