Casting And Interfaces - Comparing Object Of Unknown Types
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
ADVERTISEMENT
Aug 18, 2014
I have two different "business objects", and they have multiple attributes in common(around 25 I believe, all of which are simply a String). Basically, these objects are used for documentation purposes on the same file.
The program can choose to update a given Document at any point in time, even if changes haven't been made to existing version. So what I'm trying to do, is check to see if these attributes differ any between the two files(the exisitng copy, and the new request). If so, I'll update...else I simply throw out the request. The workload can be rather intense at times so I don't want to bog down the system anymore then necessary.
Simply pulling down every attribute for each and comparing seems like a lot of overhead, any more efficient way to achieve these results?
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
May 8, 2014
I have three classes of object, most of which must implement two out of three interfaces. The interfaces look like this:
public interface Source {
public void startSending();
} public interface Sender {
public void setReceiver();
[Code] .....
That works fine, but I am wondering if pairing the interfaces into subinterfaces is a defensible methodology. For example, all classes that act like Producer must implement both the Source and Sender interfaces. And all classes that act like Relayer must implement the Sender and BlackHole interfaces. I could define two subinterfaces like this:
public interface Factory extends Source, Sender {
}
public interface Modifier extends BlackHole, Sender {
}
I could then define my classes like this:
public class Producer implements Factory {
}
public class Relayer implements Modifier {
}
public class Consumer implements BlackHole {
}
Within the class definitions, it makes no difference, as I will have to implement the same methods either way. But it seems more self-documentary to create the subinterfaces from their parent interfaces and name them in ways that reflect what the classes that implement them must actually do.
View Replies
View Related
Mar 17, 2014
how objects relate to classes and how you can create and re-use object types.on that point, but this has me baffled. I most certainly do not have a firm grasp yet on passing things to and from methods that just makes my head hurt. SO anyway I tried out one of the code examples:
/* ElectricGuitar.java */
class ElectricGuitar {
String brand;
int numOfPickups;
boolean rockStarUsesIt;
[code]...
But I just realized this thing has no main method and only one class defined.....so I guess I just tried to compile.
View Replies
View Related
Dec 8, 2014
I need to write a class that represents and image of RGB pixels. This class uses a two-dimensional array of object type that represents R,G and B values.
When I compile the class it completes successfully. However, when I try running a "tester" class , I'm encountering errors in a few methods. I've been trying it out for 2 days now, but unsuccessfully thus far..Those method are : rotating the image by 90 degrees clockwise (and vice versa , but I just use clockwise method 3 times for that) , shifting the image sideways, and shifting the image up/down..
I've attached the whole source code for the class , and the list of errors I get when I try to run my tester. URL...
View Replies
View Related
Jul 1, 2014
Here's My Code.
package bin;
import java.util.Scanner;
public class AppletMain{
public static void main(String[] args){
Scanner oneinput = new Scanner(System.in);
String one;
[Code] ....
I am trying to get it to compare the word I type in to the set word in the object 'secretword'. I have tried everything from equal to == to compareTo, I even created a two hundred line program to do this SIMPLE problem.
View Replies
View Related
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
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
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 7, 2014
int x = 10;
do{
System.out.print("value of x : " + x );
x++;
System.out.print("");
}while( x + x == 22 );
When i put x+x==22 than it gives 2 values of x which are 10 and 11, they are wrong but when i put any other value like x+x==24 it just shows 1 value which is 10. I am not able to understand what mistake is there. I have been searching it for past whole month but didn't got any reason.
View Replies
View Related
Apr 9, 2015
I am having errors but not sure why.
My two classes. I have pointed out the lines that are causing the errors. -
import gfx.SpriteSheet;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
[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
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
Nov 24, 2014
My program compiles and runs ok how ever when i open my Jinternal frame and click on one of the JLabels i get a error on the Cmd ther error reads as follows
************************ ERROR **************************
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at JLabelAssignment.mouseClicked(JLabelAssignment.jav a:429)
at java.awt.Component.processMouseEvent(Component.jav a:6508)
at javax.swing.JComponent.processMouseEvent(JComponen t.java:3320)
[code]...
View Replies
View Related
Feb 20, 2014
So I want to know how in Java you can pass a unkown type into a method (type can be an int, double, or a user defined object) and return that unkown type.
example of what I want:
Java Code:
public (unknowntype)[] method2 ((unknowntype)[])
//Process Data
//unknowntype.process();
return (unknowntype);
} mh_sh_highlight_all('java');
I know in C you can use void pointers and in c++ we have templates but I do not know how java handles this. Also I want to know if it is possible to call a method in the unknowntype.
View Replies
View Related
Feb 17, 2015
I'm a independent IT contractor. On 2 systems this week I've experienced an issue when attempting to download JAVA the file is of an unknown type in IE. See attached. Alternative browsers on the same machine function properly.
View Replies
View Related
Apr 23, 2014
I am new to threads, This is a project about 2048 game to be more accurate, and i want this project to run in this thread that i make in main...
My main:
public class Execute {
public static void main(String[] args){
Display d = new Display();
Shell s = new Shell(d);
Model m = new Game2048Model();
View ui = new Game2048View(m.getBoardArr(),d,s);
[Code] ....
And the error is:
Exception in thread "Thread-0" org.eclipse.swt.SWTException: Invalid thread access
at org.eclipse.swt.SWT.error(Unknown Source)
at org.eclipse.swt.SWT.error(Unknown Source)
at org.eclipse.swt.SWT.error(Unknown Source)
at org.eclipse.swt.widgets.Display.error(Unknown Source)
at org.eclipse.swt.widgets.Display.checkDevice(Unknown Source)
at org.eclipse.swt.widgets.Display.readAndDispatch(Unknown Source)
at view.Game2048View.run(Game2048View.java:55) //problem at Run
at java.lang.Thread.run(Unknown Source)
Here is the problem....
@Override
public void run() {
while(!shell.isDisposed()){
if(!display.readAndDispatch()){
display.sleep();
}
}
display.dispose();
}
View Replies
View Related
Sep 2, 2014
I got stuck with the error "Unknown class" with the code that I copied from the book ...
import javax.swing.*;
class SwingDemo
{
// create a new JFrame container
JFrame MAIN_FRAME = new JFrame ("A Simple Swing Application");
// give the frame an initial size
MAIN_FRAME.setSize(275, 100);
// terminate the program when the user closes the application
MAIN_FRAME.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
[code]...
The error comes from lines 21 and 27.
21 MAIN_FRAME.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
27 MAIN_FRAME.add(FIELD_LABEL);
I have tried to rewrite from scratch and still gets the same error.
View Replies
View Related
Mar 9, 2015
I am having some issues with errors. Here is my code...
import java.io.*;
import java.util.Scanner;
public class StormChaser {
public static void main(String[] args)
{
// Constants
final int MAX_STORMS = 319;
[Code] .....
I am having issues with these error messages.... I have tried a couple of different things with each error but haven't been able to figure it out.
Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = '1'
at java.util.Formatter.checkText(Unknown Source)
at java.util.Formatter.parse(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.lang.String.format(Unknown Source)
at Storm.toString(Storm.java:98)
at StormChaser.DisplayStorms(StormChaser.java:141)
at StormChaser.main(StormChaser.java:53)
View Replies
View Related
Jul 31, 2014
I am trying to use a JFrame to open up extra windows that will prompt the user the Log In or Out, but I am getting an error with one of my variables that writes to Excel. There is something wrong with the variable "sheet" contained in the "while(i <= 4)"
private void createLabel(WritableSheet sheet) throws WriteException
{
WritableFont times10pt = new WritableFont(WritableFont.TIMES, 10);
times = new WritableCellFormat(times10pt);
times.setWrap(true);
WritableFont times10ptBoldUnderline = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD, false, UnderlineStyle.SINGLE);
[Code] .....
View Replies
View Related
Dec 8, 2014
It doesn't work and I always get UnknownFormatConversionException...
public class studentPoll {
{
public static void main( String[]args)
{
int[] responses = { 1, 2 , 5, 4, 3 , 5, 2, 1 , 3, 3, 1, 4, 3, 3, 3,
2, 3, 3, 2, 14 };
[Code] .....
View Replies
View Related