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
ADVERTISEMENT
Nov 11, 2014
I am trying to compare some items from a generic arraylist with each other, but I keep getting an error stating that I need to cast the values in line 38. However, when I heed the warning and change it to what it wants, I get a warning stating "type safety: Unchecked cast from K to Comparable<K>". Should I ignore this warning or is there a better way to compare the two items? Also, is there another way for me to use compareTo w/o making my class extending/implementing comparable or is that the only way?Here is what I have:
class WordInfo<K, V extends Comparable <K>> {
private FileReader fr;
private String word;
private ArrayList<K> list;
private BufferedReader br;
private int current = 0;
[code]....
View Replies
View Related
Aug 21, 2014
The following code snippet will print 'true'.
short s = Short.MAX_VALUE;
char c = s;
System.out.println( c == Short.MAX_VALUE);
Correct Option is : B
A. True
B. False
Explanation:
This will not compile because a short VARIABLE can NEVER be assigned to a char without explicit casting. A short CONSTANT can be assigned to a char only if the value fits into a char.
short s = 1; byte b = s; => this will also not compile because although value is small enough to be held by a byte but the Right Hand Side i.e. s is a variable and not a constant. final short s = 1; byte b = s; => This is fine because s is a constant and the value fits into a byte. final short s = 200; byte b = s; => This is invalid because although s is a constant but the value does not fit into a byte. Implicit narrowing occurs only for byte, char, short, and int. Remember that it does not
occur for long, float, or double. So, this will not compile: int i = 129L;The below code compiles fine and contradicts what is said in bold. So what does the bold statement mean then?
Java Code: class BreakTest{
public static void main(String args[])
{
float f=1.0f;
double d=f;
}
} mh_sh_highlight_all('java');
View Replies
View Related
Jun 16, 2014
I'm looking for a heuristic explanation of how to think of an "interface" as a type. I'm used to think of the 'type' of a class coming form its very definition but I often see casting to an interface which I still feel very uncomfortable about.Other than an interface, are there other unusual ways a 'type' may be referred to?
A second basic question: When you user 'super.f()', will Java go up the calling chain until it finds method 'f' (and report an err if none is found) or does it expect to find 'f' immediately at its very first parent?
View Replies
View Related
Oct 2, 2014
I have to create a program that uses the Scanner in String input and Output that will enable the user to convert
double -> int
int -> byte
int -> short
int -> hex-string
The output should look something like this:
Syntax: convert <value> <type>
convert 15.5 int~> 16
convert 128 byte~> -128
<type>: int, byte, short, hex, decimal
Syntax: max <type>
max byte~> 127
<type>: int, byte, short
[Code] ....
View Replies
View Related
Aug 3, 2014
import java.io.IOException;
import java.util.*;
public class Guesser {
public static void main(String[] args) throws IOException {
char[] alphabet = "abcdefghijklmnopqrstuvwxyz1234567890 .,:;'-".toCharArray();
[Code] .....
I'm writing a program which will take a three letter word (for now) and then try to guess the word over and over again until it finds it, then print the word and the amount of tries it took to find it.
The problem: at the moment the program will find the word but not break out of the for loop when it does. I think it doesn't like the char to String conversion somewhere along the line.
View Replies
View Related
Mar 17, 2014
how to calculate the child's height in float value fixing value where if you choose male the accurate value, but if you choose female the value will be accurate too.
int heightMother, heightFather;
int heightMaleChild, heightFemaleChild;
String gender;
[code]....
View Replies
View Related
Oct 17, 2014
why my session not type casting into String? I'm placing that code below where problem arised.
HttpSession hs1=request.getSession(false);
out.println("hi");
String t1=(String)hs1.getAttribute("name");
out.println("hi "+t1);
in my above code first "hi" is printed successfully but next statement arises type cast exception.
View Replies
View Related
Jul 15, 2014
There is a sentence in JLS 7 which I can't figure it out. It says :
A cast from a type S to a parameterized type T is unchecked unless at least one of the following conditions holds:
-S <: T
-All of the type arguments (§4.5.1) of T are unbounded wildcards
-T <: S and S has no subtype X other than T where the type arguments of X are not contained in the type arguments of T.
Condition one and two I got it. But the number three is really bugging me. I write some code in order to try to understand it.
class G<X>{}
class D<T,U> extends G<T>{}
G<String> g = new G<>();
D<String, Integer> dd = (D<String, Integer>) g;
In Eclipse I got no warning but it shouldn't give one ?
Because g has others subtypes than D<String, Integer> (e.g. D<String, List> , D<String, G>)
Am I missing something about the contained type arguments ?
View Replies
View Related
Oct 15, 2014
import java.util.*;
public class CommonElements
{
private int comparisons; // number of comparisons made
private Comparable[] arrayToSearch; // current array being traversed
private Comparable[] commonElements = new Comparable[10];
private int arrayPosition = 0; //keeps track of what index to add an element to common at
[Code] ...
I have trying to get this down to the bar minimum. I am trying to cast the desired object array to a array of comparable. This is all required by the assignment.
I am getting a runtime error that I can not perform the desired cast. What do I need to provide the compiler in order to allow for this casting. I can not change the signature of the method however nothing about the class has been specified do I need to implement comparable? Also I don not now what the client is passing so how would I write a generic compareTo method to compare object of unknown types.
View Replies
View Related
Jun 7, 2013
"Type Casting" .... So the question is "How am I getting a number with two decimal places as output?"
import java.util.Scanner;
public class SalesTax
{
public static void main(String[] args) {
double purchase, tax;
Scanner input = new Scanner(System.in);
System.out.print("Enter purchase amount: ");
purchase = input.nextDouble();
tax = purchase * 0.06;
System.out.println("Sales Tax: $" + (int)(tax * 100) / 100.0); +//this will give two decimal places??+
}
}
View Replies
View Related
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
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
View Related
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
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
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
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
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
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
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
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
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
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
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
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
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