Using Comparable Interface Between Two Classes
Feb 13, 2014
I have the following code that will make linked list and order its elements using self referential objects. but i have the following error:
incompatible types
required: ListNode<T#2>
found: ListNode<T#1>
where T#1,T#2 are type-variables:
T#1 extends Comparable declared in method <T#1>insertInOrder(T#1)
T#2 extends Comparable declared in class OrderedList
import java.util.*;
public class ListNode<T> {
ListNode<T> nextNode;
T data;
public ListNode(T item)
{
this(item, null);
[code]...
View Replies
ADVERTISEMENT
Jan 1, 2014
I have a task to create a Java OOP program, I have a class Team which requires a comparable and iterable interface, the only way I know how to do this is either:
public class Team implements Iterable <Mechanic>
or
public class Team implements Comparable <Mechanic>
How do I add both?
View Replies
View Related
Oct 31, 2014
Here is my code:
/*
* Implement the Comparable interface on objects of type Order.
* Compare orderId, then productId. The lesser orderId should come first. If the orderIds match, then the lesser productId should come first.
*/
@Override
public int compareTo(Order ord) {
// TODO Auto-generated method stub
if(orderId > ord.orderId){
return 1;
[Code] ....
Here is the output:
Actual: 0
Expected: -1
Actual: -1
Expected: -1
Actual: 1
Expected: 1
Actual: 1
Expected: 1
Actual: 0
Expected: 0
Actual: 0
Expected: 0
In short, the "Actual" is what my code produces and the "Expected" is what it is supposed to produce. As you can see, only the first one is mismatching... I'll admit, the comment section above the method is confusing and I wasn't exactly sure what it wants me to do, but I thought I figured it out. I just don't see how 5/6 of these tests can work and the 6th one not.
View Replies
View Related
Apr 16, 2014
Why is it necessary to implement the comparable interface for primitive types and not for classes such as Integer, String etc . . . ?
View Replies
View Related
Mar 15, 2014
Below is the requirements and code. I am getting the error CODELAB ANALYSIS: LOGICAL ERROR(S)We think you might want to consider using: >
Hints:
-Correct solutions that use equals almost certainly also uses high
-Correct solutions that use equals almost certainly also uses low
Assume the existence of a Widget class that implements the Comparable interface and thus has a compareTo method that accepts an Object parameter and returns an int . Write an efficient static method , getWidgetMatch, that has two parameters . The first parameter is a reference to a Widget object . The second parameter is a potentially very large array of Widget objects that has been sorted in ascending order based on the Widget compareTo method . The getWidgetMatch searches for an element in the array that matches the first parameter on the basis of the equals method and returns true if found and false otherwise.
public static boolean getWidgetMatch(Widget a, Widget[] b){
int bot=0;
int top=b.length-1;
int x = 0;
int y=0;
while (bot >= top)
[code]....
View Replies
View Related
Dec 15, 2014
How do you enforce any class which implements an interface should also implement comparable too? Say for instance you may have an interface
public interface Task
{ ... }
public class DoThis implements Task { ... }
public class DoThis1 implements Task { ... }
I want all of the classes which implements the interface Task to implement comparable too. Of course I can just say implements Task, Comparable. But is there something which we could do from interface level, i mean interface Task level?
View Replies
View Related
Apr 13, 2015
Which of the following classes uses Comparable and Comparator?
QueueTreeSetStackPriorityQueue
In the above question, what does 'uses' mean? Does it mean do above classes implement Comparable and Comparator?
I know that in order to compare any two elements stored in one of the above classes, we need to make the elements' class to implement one of these - either Comparable or Comparator.
View Replies
View Related
Jun 4, 2014
why don't I define my methods in a class, rather than going a level up and declaring it first in an abstract class/interface? If the point is to have different implementations for different needs, then we have the option to override the methods.
View Replies
View Related
Oct 20, 2014
I am new to Java, and last week had an assignment to create a shopping list. I made it so that I have one class use a ProductData class to load an array of objects (description, price, priority). This week I need to take that program and change it so that it includes an Interface and Abstract Class. I need to also split one class up into at least 2 others.
I am having trouble getting my thoughts together and figuring out what to put in the interface and what to put in the abstract class. I'm thinking that it might be best to split up the ProductData class up into 3 different classes: description, price, and priority. Then have an interface with a print method. Each of those 3 classes will implement the interface.
As for the abstract class, have the price and priority extend the abstract class. The abstract class will be at the same level as the interface and contain the set and get methods. Right now they are of 2 different data types: int, double. Should I make both of them Double, and then use a method to change the priority to an int?
Should price and priority inherit from description, or should they all be at the same level? I am thinking that they should be at the same level because they all describe the item in the array.
My most confusing part is that I have no clue at all on how I can load that array when each object is split up in a different class. My professor went over ArayLists last week, and we can now use them if we want, but the assignment doesn't explicitly say that we should change it to an Array List. Where does the constructor for the ProductData() go? Do I split it up into 3 different constructors?
View Replies
View Related
Nov 29, 2014
If I lets say have an interface Animal, and I create a lot of classes with a different animal name that implement the interface Animal. Then I create an ArrayList of Animal. Then I would put in lets say Dog class into the ArrayList, which has custom methods and data that the Animal Interface doesn't have, is this data ripped away except for the methods that are put in the Animal interface? So if I would cast the Animal back to Dog, would it retain all the data that existed before it was placed in the ArrayList?
View Replies
View Related
Jan 8, 2014
I am writing a game in Java for Android (although my question isn't Android or Game Dev specific).
I have a SceneManager class and a Scene interface and then various other classes that implement the Scene interface (Code at the end of this post).
Basically, in my MainGame class (which also implements the Scene Interface for Touch Event capturing purposes) I hold the bulk of my game code. Methods in this class are then called from my Level classes. (most of these are needed in all levels so it makes sense to hold them here and call them from the levels to eliminate unnecessary code duplication)
So, I have Level1, Level2......... Level20 classes which all implement Scene.
Now, the problem comes because in only 2 of my Levels something can happen (that can't in the other 18) and I need to run a response method in these 2 levels (the method isn't exactly the same, the response to this event happening is different for both levels).
To run common methods from my classes, I use my Scene Manager like this:
SceneManager.getInstance().getCurrentScene().updateLogic();
SceneManager.getInstance().getCurrentScene().render();
(The above is from my gameloop) - So it will run the updateLogic(); and render(); methods from whichever is the current scene (Level).
Scene is changed like so:
SceneManager.getInstance().setCurrentScene(LevelX);
This works great as all Level's have an updateLogic(); and render(); method.
So from my mainGame class, I am doing something like : (pseudo code)
public void checkIfSomethingHappened(){
if (something happens){
if (currentLevel==5){
Level5.response();}
[Code]....
The above would be called from my 2 level classes. So something like:
MainGame.checkIfSomethingHappened(); //Called in addition to the normal methods that make up that level
I don't really want to have this (second) 'if' statement here in the middle of my performance critical game loop.
What I'm after is something like this:
if (something happens){
SceneManager.getInstance().getCurrentScene().response();
}
However, this would require me to put stubs in the other 18 classes.
I'm thinking there must be a way to do this as the SceneManager already knows the current scene so it seems a waste checking it again via an if (or switch) statement. What is the best way to do this without having to put stubs into classes that don't require this method?
View Replies
View Related
Apr 14, 2014
I am new a creating GUIs and am not quite sure how to correctly make one. I have done the inheritance parts, and created two extra appliances: a washer and dryer. Now Creating the GUI ....
Here are the instructions to my project.
Introduction to GUIs (+ some inheritance)
For this assignment, you are going to create a user interface that interacts with the setters and getters of some classes that you will create.
First, create an abstract class called Appliance. This abstract class should have two attributes (dealing with household appliances) and two abstract methods called turnOn() and turnOff(). These methods should return void.
Then, create two subclasses of Appliance that represent household appliances (like a Refrigerator or Stove ((don't use those!))). These subclasses should have two attributes that are specific to the various appliance. Each subclass should implement the turnOn() and turnOff() methods. These methods should print to the command line some information about the appliance as it turns on and off.
Now, the fun part! Create a GUI interface!
Your window should have two panels: one for each appliance subclass. Each panel should have 4 textboxes (with appropriate labels) to receive/display information that correspond to the 4 attributes (2 from Appliance and 2 from the subclass) for each subclass.You also need 2 buttons on each panel: A Get button and a Set button.
When the Get button is pressed, the text boxes should be filled with the information from the instantiated object of the appropriate subclass. When the Set button is pressed, the object should then contain the information contained that the user has altered.
In your main method, you should create an object of each subclass, and prefill it with information (either using the constructor or the setters), then display your GUI. You should now be able to get and set the information for your objects from the GUI.
At least one of your attributes for each subclass should be numeric
Note that you will need to handle incorrectly formatted input (You can use exception handling to do this if you want to. Wrapper classes also will work)
If there is text in the boxes when the "Get" button is pressed, it should be overwritten by what is in the object. Remember that these two panels should both be on screen at the same time.
You don't need 2 different windows, one window: 2 panels.
View Replies
View Related
Jan 24, 2014
I am asked to create a code that if a user enters 1 it will use the object natural comparison form ('default') as written in CompareTo method.But if he chooses to enter something else then another comparison is used.Maybe I just need to use 2 diff comparators? but then what;s the point of defining something as 'default'....
View Replies
View Related
Jun 1, 2014
I have big problem with mergesort in Java. I can't figure out why it do not works. I need write it on lists using Comparable. Here is piece of code:
Java Code:
class MergeSort{
Comparator _comparator;
List lista = new ArrayList<>();
List list_temp = new ArrayList<>();
MergeSort(Comparator comparator){
[Code] ....
I have tried everything, still no results. It's return list with random placed numbers.
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
Jul 1, 2013
I was going through some lectures online and found that to compare or even swap, the use of comparable or comparator argument like
public static boolean less(Comparable v,Comparable w)
{
return v.compareTo(w)<0;
}
public static void swap(Comparable []a,int i,int j)
{
Comparable swap=a[i];
a[i]=a[j];
a[j]=swap;
}
I did not get the use of passing Comparable or Comparator to the function as parameters. Object as parameter could have been used too?
View Replies
View Related
Apr 19, 2014
I am working on an assignment that requires me to implement 2 methods (add() and remove()) and create an inner class (OrderedListNode). I must use data items of type Comparable. The items should be sorted.
I understand what needs to be done, but I am having a difficult time actually writing the code. I added the main method to check to see if my code works, and it doesn't seem like that is even being read.It compiles without error - it only gives a warning of unchecked or unsafe operations.
Code:
package dataStructures;
//This class functions as a linked list, but ensures items are stored in ascending order.
public class OrderedLinkedList {
//return value for unsuccessful searches
private static final OrderedListNode NOT_FOUND = null;
[code]...
View Replies
View Related
Feb 24, 2014
Operator is undefined for argument type. Error is located at the end of the binary search method array[position] < key
import java.util.Arrays;
public class binarySearch {
public static <T extends Comparable<T>> int binarysearch(T key, T[] array) {
int start = 0;
int end = array.length - 1;
int position =-1;
while (start <= end && position == -1) {
[Code]....
View Replies
View Related
Oct 9, 2014
My assignment was to create a priority queue for Airline Passengers. Here is what I have done so far:
//Driver
package priorityqueuestandby;
import java.util.NoSuchElementException;
import javax.swing.JOptionPane;
public class PriorityQueueStandBy {
public static void main(String[] args) {
[Code] .....
So the part that I cant figure out is:
When a standby passenger is to be enqueued into the priority queue, it must be done so that at the moment of each dequeue operation, the item at the head of the queue is the standby passenger with the longest longevity, and also so that passengers with the same longevity are dequeued in a first-come-first-served fashion.
he says that we need to "Make your program so that it extends Comparable and implements the compareTo() method properly..."
So I was looking at the Comparable class and I could't find a compareTo() method... I am not confident I know how extends works either. I am assuming I need a new class if I am going to be extending another class. Right now I am taking in longevity as a String and converting it to an int because my last ditch effort is going to be to set up a loop that will organize longevity into a/an circular array based on the size of the incoming integer.
View Replies
View Related
Jun 9, 2014
Below code gets printed as output?
public interface I1 {
public void method();
}
public interface I2 {
public void method();
}
public interface I3 extends I2, I1 {
[Code] ....
View Replies
View Related
Apr 18, 2014
How do you call classes within other classes? Or can you only call classes through the main?
View Replies
View Related
Oct 27, 2014
The term "Local variable" is related to scope. That is a local variable is one which is defined in a certain block of code, and its scope is confined inside that block of code.And a "Member variable" is simple an instance variable.
I read in a discussion forum that when local variables are declared (example code below), their name reservation takes place in memory but they are not automatically initialized to anything. On the other hand, when member variables are declared, they are automatically initialized to null by default.
Java Code: public void myFunction () {
int [] myInt; // A local, member variable (because "static" keyword is not there) declared
} mh_sh_highlight_all('java');
So it seems that they are comparing local variables and member variables. While I think a member variable can also be be local in a block of code, isn't it?
View Replies
View Related
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
Feb 5, 2014
I have following code. In this code CSClient is an interface. All methods of CSClient are implementaed in CSClientImpl class. Do I not need CS Client Impl imported in this code ?
How can I call getBranch() of CSClient, which is not implemented in CSClient as " this. getCsClient(). get Branch (new CSVPath(vpath), true);" ? This code works fine without any error in eclipse.
How can a method getBranch(), which is implemented in CSClientImpl class be used in this code without importing CSClientImpl ?
package com.rbc.teamsite.client;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
[code]....
View Replies
View Related
Jan 21, 2015
Variables defined in interface are public static and final so I was thinking that we should not be able to override the variables in a class thats implementing the interface. But when I am compiling the below class, it compiles fine and gives the correct values. but when I did disp.abhi = 35; it gives a compile error (cannot override final variable)
interface display{
int abhi = 10;
void displayName();
[code]....
View Replies
View Related
Nov 24, 2014
what is marker interface?i want to know internal implemenatation and how to write custom marker interface?
View Replies
View Related