Clarify Generics For Classes

Jun 19, 2014

I just want to clarify generics for classes.

Referring to [URL] ....

Generics means all methods in class Box will return an Integer if their parameters are defined as T when the instantiation is :

Box<Integer> integerBox = new Box<Integer>();

Are those Boxes only can contain Integers? Can I write

Box <Toys> toybox = new Box <> ();

To show that the Box only contain toys?

View Replies


ADVERTISEMENT

Integer Sum In Generics

Mar 20, 2015

What is wrong in this

class Gen<k,v>
{
K a;
V b;
Gen(K s, V f) {
a=s;
b=f;

[Code] .....

a is object of type k,then how can I retrieve content of a?

View Replies View Related

Casting Exception In Generics

Jan 29, 2014

I have studied that Generics are used to shift the Class Cast Exception into Compile time errors , So that we get errors at compile time error and we do correct them before executing ,but Here is a program in which i am getting Class Cast Exception

class Animal
{
}
class Dog extends Animal
{
}
class Cat extends Animal

[code]..

Getting Exception at line no 29 which i know why it occurs but just wanna ask that isn't it should be caught at compile time According to Generics ?

View Replies View Related

Java Generics Super And Ext

Jun 17, 2014

Set<? super TreeMap> s = new HashSet<SortedMap>();

SortedMap<String,String> sm = new TreeMap<String,String>();
TreeMap<String,String> tm = new TreeMap<String,String>();
s.add(sm); //This fails
s.add(tm);

Why does adding sorted map to a Set that allows ? super TreeMap and instantiated as such fail?

View Replies View Related

Returning Int Array Using Generics

Apr 10, 2014

public int[] allIndicesOf(E itemSought) {
ArrayList<Integer> toUse = new ArrayList<>();
for (E anArray : container) {
if (anArray.equals(itemSought)) {
toUse.add(container.indexOf(itemSought));

[Code] ....

I have an array list of strings. I want to be able to return an array of integers telling me which indexes in the string array list contain the itemSought object.

View Replies View Related

Generics Super Keyword

Feb 14, 2014

Suppose I have

class A {
public void speak() {
System.out.println("I am class A");
}
}

class B extends A{
public void speak() {
System.out.println("I am class B");
}
}

class C extends B{
public void speak() {
System.out.println("I am class C");
}
}

Why this doesn't work while A is a super type of B ?

public static void insertElements(List<? super B> list){
list.add(new A()); //not OK, why?
}

View Replies View Related

Why Use Extends Keyword Instead Of Implements In Generics

Feb 22, 2015

Why java uses the keyword extends when setting the bound of a type parameter(Generic) to an interface. I think using the keyword implements is more intuitive.

public static <T extends Comparable<T>>

why use extends? and not implements.

int countGreaterThan(T[] anArray, T elem) {
int count = 0;
for (T e : anArray)
if (e.compareTo(elem) > 0)
++count;
return count;
}

I know if I want to set multiple bounds I will use extends keyword, and I will concatenate the bounds using & operator.

Is this a design decision to always use extends keyword to set bounds?

View Replies View Related

Generics Wildcard Array Of References?

Jul 27, 2014

An array of references to a specific generic type is not allowed in Java.

e.g.,

ArrSpec<String> arrs[] = new ArrSpec<String>[10];

is not allowed though the type checkng and memory allocation can be done at the compile time itself.

Instead of this, Java allows to use Wildcard type array of references to a generic type.

e.g.,

ArrSpec<?> arrs[] = new ArrSpec<?>[10];

is allowed though the type checking, memory allocation and any type of values to be stored would be decided at the runtime.

View Replies View Related

Generics In Java - E Is A Subtype Of Comparable

Jun 5, 2015

My book defines this generic method

Java Code:

public static <E extends Comparable<E>> void sort(E[] list... mh_sh_highlight_all('java');

Comparable is an interface and from how i look at this piece of code is that I can only use a class that implements the Comparable interface; however, this is the context my book uses when explaining the following code

First, it specifies that E is a subtype of Comparable.

Second, it specifies that the elements to be compared are of the E type as well.

What does it mean when it says E is a subtype.

View Replies View Related

Generics And Inheritance - Specialized Methods

Mar 6, 2014

I've an interface with generic methods in it. I would like to have specialized methods in the sub types. While doing that I'm seeing the following warnings in eclipse.

class Sorter {
<E> void sort(E[] elements);
};
 
class StringSorter {
 
// This gives me a warning 'hiding' to 'sort'
<String> void sort(String[] elements) {
}
 
// Gives me an error "The method someCrap(String[]) in the type StringSorter is not applicable for the arguments (String[])"
void someCrap(String[] elements) {
}
};

I would like to understand why eclipse gives the above warnings and errors.

View Replies View Related

Upcasting And Downcasting Rule For Object And Generics?

Dec 15, 2014

is the Java upcating and downcasting rules are same for general object type or generics types?

1) Dog dog = new Animal();

Type mismatch can't covert Dog to Animal - complie time error

2) Animal animal = new Animal();
Dog dog = (Dog) animal;

java.lang.ClassCastException: Animal cannot be cast to Dog at runtime.

View Replies View Related

Doubly Linked Lists And Using Java Generics

Oct 25, 2014

I'm working with Doubly Linked Lists and using Java Generics..

My nodes looks like this:
class DNode<E> {
DNode<E> previous;
DNode<E> next;
E element;

//and all methods inside
}

My list of Nodes looks like this:
class DLL<E>{
private DNode<E> head;
private DNode<E> tail;
private int size;

[code]....

As you can see, as arguments they get "E o"...I need to write a program, which from the main function asks the users how long is the list, and after they type it's length, I ask them to start typing the elements (integers)...and this is how my main method is written, but I can't seem to make it work, specialy when I call the "insLast" method,I guess it's because the arguments i'm giving to the function...how to read the elements and write them into the list?

public static void main(String[] args) throws IOException {
DLL<Integer> lista=new DLL<Integer>();
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String s = stdin.readLine();
int N = Integer.parseInt(s);
s = stdin.readLine();
String[] pomniza = s.split(" ");
for (int i = 0; i < N; i++) {
lista.instLast(Integer.parseInt(pomniza[i]));
}

}

View Replies View Related

Add Only String And Integer To ArrayList By Using JAVA GENERICS

Aug 27, 2014

i am interested to add integer objects and String objects into any collection object ..... while iterating the collection object i am not interested to do any type cast in java

View Replies View Related

First Time Using Generics - Incomparable Type Errors

Aug 29, 2014

I am trying to make a generic method that will replace the data type T with those number types usable with a Scanner object. However, whenever I try to compile, I get errors saying that a Byte/Integer/Double etc are found when only a type T is allowed. This is the beginning of my method. I can;t understand what is wrong with it.

Java Code:

public <T extends Number> T nextRanged(T lowerBound, T upperBound, boolean inclusive, String errorMessage){
// Holds program execution until user inputs a numeric value between the bounds. Prevents all other input without exception.
// Output data type determined by the type of the bounds.
T input = null;
try{
if(input instanceof Byte){
input = new Byte(internalScanner.nextByte());

[Code] ....

The purpose of the method, in the end, will be to provide the nextXXX() functionality of a Scanner object but with built in validation procedures. I could easily do this by making a nextIntRanged(), nextDoubleRanged() etc methods, but this seems wasteful to me.

I meant "incompatible type errors"!

Error example:

ValidatedScanner.java:57: error: incompatible types
input = new Byte(internalScanner.nextByte());
^
required: T
found: Byte

where T is a type-variable:

T extends Number declared in method <T>nextRanged(T,T,boolean,String)

View Replies View Related

Erasure Feature From Generics - Duplicated Bound Error

Jun 14, 2014

The erasures of all constituent types of a bound must be pairwise different, or a compile-time error occurs.

Well I know what type erasure is, and I think I kind got what this statement means. My understanding from it is that if your type parameter has more than one bound and those bounds occurs to be the same type after erasure that is a compile-time error. Is that it?

The only thing I could found related is something like this:

class A<T extends List<Integer> & List<Integer>>{
}

Which as you might know gives the Duplicated bound error.

View Replies View Related

Java Generics - Why Cannot Use Primitive Data Type Like Int / Double

Feb 21, 2014

I have doubt in generics,

List<int> c=new ArrayList<int>();

why we cannot use primitive data type like int,double.

View Replies View Related

How To Call Classes Within Other Classes

Apr 18, 2014

How do you call classes within other classes? Or can you only call classes through the main?

View Replies View Related

Passing Values To Two Classes And Retrieving Values From Those Classes

Feb 14, 2015

I'm doing an aggregation exercise that's suppose to find the volume and surface area of a cylinder. What I'm trying to do is pass values from one class, to a second class, and that second class passes values to a third class.

This may be a clearer explanation: The first class is the main program which sends values to the second and third class. The second class is used do calculations for a circle (a pre-existing class from another assignment). The third class grabs the values that the second class calculated and calculates those values with the one that was passed from the first class to the third class. The first class then prints the outcome.

Problem is when the program gets to the third class, it just calculates the value from the first class with the default constructor from the second class. It's like the second class never received the values from the first class. I think I'm missing a step, but I don't what it is.

First Class:

package circle;
import java.util.Scanner;
public class CylinderInput
{
static Scanner in = new Scanner(System.in);
public static void main(String[] args)
{
//user defined variable

[Code]...

View Replies View Related

Inner And Anonymous Classes

Dec 26, 2014

Why do we get such output or which line of code produces the output?

1class Egg2 {
2 protected class Yolk {
3 public Yolk() { print("Egg2.Yolk()"); }
4 public void f() { print("Egg2.Yolk.f()");}
5 }
6 private Yolk y = new Yolk();

[Code] ....

/* Output:

1.)Egg2.Yolk()
2.)New Egg2()
3.)Egg2.Yolk()
4.)BigEgg2.Yolk()
5.)BigEgg2.Yolk.f()
*///:~

View Replies View Related

How To Get Two Classes To Get Objects From Each Other

Oct 18, 2014

I'm quite new to Java. I have some trouble with understanding how to get two classes to get objects from each other (if that is the correct term).

Lets say I have a login class, in which I have a method checking what the user has entered into the console (I have not displayed the whole code, but this class works as it should and give the user an option to enter username and password and return it true if entered correct).

public static boolean validateUserPass(String userName, String password) {
String[] user = {"admin"};
String[] passwords = {"firkanten"};
boolean check = false;
for (int i = 0; i < user.length; i++) {
if (userName.equals(user[i])) {
if (password.equals(passwords[i])) {
check = true;

Now, in another class I want a display box to appear on the screen and give the user three options: Click yes, no or cancel. I get this to run perfectly alone, this is not the hard part for me. I want the display box only to appear when the correct username and password is given, but I can't seem to figure out how to do this probably.

View Replies View Related

Using Same Variable Name In Two Classes

Feb 7, 2014

Regarding the code examples in Head First Java, this is from Chapter 5, regarding the beginning creation of the dot com game. There are two classes in quesiton

the first is the SimpleDotComTester class:
public class SimpleDotComTester {
public static void main(String[] args)
{
SimpleDotCom dot = new SimpleDotCom();
int[] locations = {2, 3, 4};
dot.setLocationCells(locations);
String userGuess = "2";
String result = dot.checkYourself(userGuess);
}
}

and the second one is the code for the checkYourself () method in the SimpleDotCom class

public class SimpleDotCom {
int[] locationCells;
int numOfHits = 0;

public void setLocationCells(int[] locs)

[code]....

Now I noticed that both classes use a variable called result; the program runs fine, but assume from the example that you can use the same variable name two different classes;

View Replies View Related

How To Design Classes

Mar 29, 2014

design a class to conduct a survey of three hospitals. you want to know how many sectors (eg operation, children, gastronomic) each hospitals have, and how many doctors there are in each sector.

what is the process of class design?

View Replies View Related

Integrating 2 Different Classes

Jan 5, 2014

I have a Date class and Time class. Is it possible to pass Time object inside Date constructor so that toString function gives output as 12/05/2013 06:31:30 ?

View Replies View Related

How To Associate Two Classes

Apr 24, 2014

I have two classes.

First and Second.

In First class I want to use methods from Second class. So:

Java Code:

Second s = new Second();
s.secondMethod(); mh_sh_highlight_all('java');

Second thing I want to do is use JTextArea from First class in Second class.

So since it gives me error, I extended First class with Second:

Java Code: public class Second extends First { mh_sh_highlight_all('java');

It look like it should work, no errors etc. Also both things are working separately. But since I used both at once...

Java Code:

Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
at package.Second.<init>(Second.java:7)
at package.First.<init>(First.java:17) mh_sh_highlight_all('java');

I can move what I need to First class, and it will work fine, but I want to make this in two classes. But I really don't understand extends, I just use them if there is need for them. So I don't know how to handle this problem.

I also tried to extends Second just like First:

Java Code: public class Second extends JPanel implements ActionListener { mh_sh_highlight_all('java');

Instead of extending First, but it can not be done, since ActionListener is in First...

Well. Also addActionListener can maybe solve my problem?

I'm using:

Java Code: xx.addActionListener(this); mh_sh_highlight_all('java');

Maybe I can use something instead of this? But what?

View Replies View Related

When To Use Inner Classes In Java

Jan 19, 2015

Wondering, what is exactly reason for existence of inner classes? Are there problems that without them you can not resolve?

Anything beside emulate multiple inheritance - when your class need to extends the real classes, and not implement multiple interfaces ?

View Replies View Related

Add Only Some Classes To A Package?

Mar 28, 2015

I have a folder of classes that I am packaging together. Some classes are being packaged and compiling just fine. My other classes in the same package, however, are saying that they cannot find these classes.

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved