Implementing Comparator Interface?

Mar 7, 2014

overriding of the compare method.

Here's an example I found:

public class Someone {
String name;
int age;
ArrayList <Someone> listarr = new ArrayList <Someone>();
public Someone(String name1, int age1) {
name = name1;
age = age1;

[code]...

1. In the compare method, what happens when it returns one of the 0, -1, or 1? How does returning such values contribute to the sorting process? How does it take in information (like I know it does through the parameters, but how exactly)?

2. Why do we use the class name for the generics?

View Replies


ADVERTISEMENT

Comparator Interface Implementation?

Mar 6, 2014

Something about implementing Comparator interface isn't very clear to me: overriding the compare method.

Like here for example:

//This sorts a list of objects holding information based on age: the name and the age of the person
 
public class Person {
String name;
int age;
public Person (String name, int age)
{
this.name = name;
this.age = age;

[Code] ....

What exactly is happening behind the scenes? I don't understand mostly the part where it returns a 0, a 1, or a -1. After it returns one of those values, what really happens next?

For the displaying of the list, is the method toString() being accessed to output the list in the System.out.println statement?

For the generics, why do we use Person?

View Replies View Related

Comparing 100 Objects Using Comparator Interface In Java?

Jul 4, 2014

Is it possible to compare 100 objects using comparator interface in java?

View Replies View Related

Implementing Custom Map Interface

Nov 5, 2014

I am supposed to implement a custom Map interface and I'm having some trouble with this method:

// 1. From the interface
/**
* Gives an iterator iterating over the key set from the smallest key that is not less than the key provided.
* @param key the key
* @return the iterator
* @throws NullPointerException if key == null
*/

public Iterator<Key> tailIterator(Key key);

[Code] .....

My implementation is wrong according to a JUnit test. Also, to get a full score this method should have a worst case running time of O(log N), which obviously isn't the case now. (My Map implementation is currently based on binary search in an ordered array, keeping a prallel array for the values).

View Replies View Related

Sorting With A Comparator

Mar 26, 2014

I am trying to sort an ArrayList of objects with the comparator as I want to sort based on a certain value for each object. I understand I would need to override compareTo() in the objects class, is there any way I can get around also needing to override for all subclasses of the object?

View Replies View Related

What Is Comparator In Sorted Set

Jul 11, 2014

I read the document [URL] ....

But I am not able to get what is actual use of this in set ?

View Replies View Related

Can Mix Comparable And Comparator

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

Binary Search And Comparator

Aug 2, 2014

If an array has been sorted using a comparator then why is it necessary to pass on that comparator to the binaryserach method. What I want to know is that how come the presence of a comparator reference affect the way the algorithm works?

View Replies View Related

Writing Own Custom Comparator In Java

Jul 27, 2014

I have a java code that should sort an array of names based on the last name. e.g jane a, jane b, jane z, jane d should be jane a, jane b, jane d, jane z. I have the following code but for some reasons, the s1 in the comparator method is always null.
 
public class ShuffleName {
public static void sortNames(String[] names){
 Arrays.sort( names, new Comparator<String>() {
 public int compare( String s1, String s2 ) { 
String s1last = s1.split("s+")[1];
String s2last = s2.split("s+")[1];
return s1last.compareTo(s2last);

[code]....

View Replies View Related

How To Determine If Classes Use Comparable And Comparator

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

Using Comparable Or Comparator As Parameter In Method

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

Comparator - No Suitable Method Found Error

Apr 24, 2014

So I built this comparator exactly the same way I built my others that are working.But the comparator for UserComparator is not being found for some reason.I will post my usercomparator class and JSP page.

<%@page import="tickets.UserComparator"%>
<%@page import="tickets.User"%>
<%@page import="tickets.ReporterTTComparator"%>
<%@page import="tickets.StatusTTComparator"%>
<%@page import="tickets.SystemTTComparator"%>
<%@page import="java.util.Collections"%>
<%@page import="java.util.ArrayList"%>
<%@page import="tickets.TroubleTicket"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>

[code]....

View Replies View Related

Text File - No ArrayList Or Comparator Is Allowed

Feb 15, 2015

The initial output of the texfile is this. NO ARRAYLIST OR COMPARATOR IS ALLOWED:

Steve Jobs 9 f 91
Bill Gates 6 m 90
James Gosling 3 m 100
James Gosling 3 f 100
Dennis Ritchie 5 m 94
Steve Jobs 9 m 95
Dennis Ritchie 5 f 100
Jeff Dean 7 m 100
Bill Gates 6 f 96
Jeff Dean 7 f 100
Sergey Brin 27 f 97
Sergey Brin 22 m 98

The collateExams method collates/sorts exam objects starting with the first 'm' (midterm) of the first object and immediately followed by the same person's 'f'(final). Only a SINGLE loop construct is allowed. The output from collateExams() should be the one below but my code is not working, i.e. collateExams method is not working. The output from collateExams() should be

Bill Gates 6 m 90
Bill Gates 6 f 96
James Gosling 3 m 100
James Gosling 3 f 100
Dennis Ritchie 5 m 94
Dennis Ritchie 5 f 100
Steve Jobs 9 m 95
Steve Jobs 9 f 91
Jeff Dean 7 m 100
Jeff Dean 7 f 100
Sergey Brin 22 m 98
Sergey Brin 27 f 97

I am getting [b]NullExceptions[/b] at

r[2*position[exams[i].getID()]+1] =
new Exam(r[i].getFirstName(), r[i].getLastName(),
r[i].getID(), r[i].getExamType(), r[i].getScore());

import java.io.*;
import java.util.*;

[Code] ....

View Replies View Related

Sort 2 Different Objects In Self Made Generic Class Using Comparator

May 31, 2014

Ok here are my 2 Classes

Both have Identical Fields

package com.Lists;
public class EmployeeOffice implements EmpInterface {
private double salary;
private String name;
private String postion;
private double hoursWorked;

[Code] .....

So if i wanna sort this Generic class using comaparator what do i do... I cant find an answer to this... I wanna sort them on the basis of salary what to do ...

View Replies View Related

Interface Extends More Than One Interface

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

Implementing A FPS Counter

Jan 17, 2014

Ok, so I'm making a game with a space ship that flies around the universe and discovering new planets. It works fine so far, but I'm looking to make it perform better and be better compatible with lesser-processors.So, I'm trying to put in an FPS counter and an entirely new game loop so that my game can decide for me what FPS I should use.

I have two classes. Heres the big, main one: [Java] package cyentw.game.src; import java.awt.Color; import java.awt.Font; impor - Pastebin.com *I want to change the loop and put an FPS counter in around line 456, you can scroll past the rest if you'd like*And heres the init frame one, in case you'd like to see it for some reason.

Java Code:

package cyentw.game.src;
import javax.swing.JFrame;
public class Start extends JFrame{
public static JFrame frame;
public static int WIDTH = 500;
public static int HEIGHT = 500;
public Start() {

[code]....

how to make my game loop as quickly (or a bit slower) as it can, and my FPS is static.

View Replies View Related

Swing/AWT/SWT :: Implementing JTabbedPane GUI?

Aug 21, 2014

I have been trying to learn how to use the TabbedPane GUI. I can get the tabs to show up, but the buttons I have placed in each tab do not show up. Why this is not working. I assume that, for some reason, the buttons are not linking with their respective panels, or the panels are not linking to the respective tabs.

import java.awt.BorderLayout;
import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

[Code] ....

View Replies View Related

Implementing Two Stack In One Array?

Jan 5, 2015

is this program correct? for Implementing two Stack in one array. how can i solve it ?

public class Stackation11 {
int max = 10;
int [] array = new int[max];
int top;
int top1;
Stackation11(){

[code]....

View Replies View Related

Implementing Breadth First Search

Dec 13, 2014

I have always wanted to program A*, Breath First Search and Depth First Search ever since I took AI. I will only post BFS at the moment but it is only searching the row.

Java Code:

//Breath First Search. The first node passed to it is the start button
void bfs(Mybuttons button){
Queue<Mybuttons> q = new LinkedList<Mybuttons>();
q.add(button);
button.setIcon(button.setButtonToBlueWhileSearched());
button.model.visted=true;

[Code] ....

Output:

Java Code: In while loop
In get Child Node
In get Child Node
In get Child Node
In get Child Node
In while loop
In get Child Node
In get Child Node
In get Child Node
In while loop
In get Child Node
In get Child Node
In while loop
In get Child Node mh_sh_highlight_all('java');

View Replies View Related

Implementing Deserialization Of Objects?

Jul 16, 2014

Say you have a bunch of animals, `Rat` `Cat` `Dog` and `Fish`, and you want to serialize/deserialize these animals. Each has its own `serialize()` method. That all works fine and good, if you want to save your Cat to a file, you call `Cat.serialize()` and then you write it to a file.

But what about deserializing? Sure, you could save an extra bit of data that states the type of animal, then use reflection to get a static method (say, `deserialize(String serialized)`) and then invoke it. But that's not safe. What if someone creates a new animal 'Rabbit' and doesn't include a `deserialize(String serialized)` method? Sure, you could then just catch the error and ignore the issue, but that seems unclean and bad practice.

You could also create an enum. Each item in the enum must have a `deserialize(String serialized)` method, and the aforementioned piece of data that states the type references the name of its enum item. Problem is, not very adaptable. Enums don't allow for other animals to be added at runtime.

The way I have been solving this issue is mapping the name of the objects against a deserializer object. Basically each animal would have to 'register' itself by entering it's name and deserializer (implements `Deserializer` interface) object into a HashMap. The deserializer object can then be retrieved via the name of the animal at a later time.

My question is, what is the best method to go about implementing deserialization? Also, is the method I have been using good/bad practice?

Finally, if you are wondering why animals would be added at runtime, the reason is because animals might be added by other non accessible parts of the program, or by things such as plugins.

Example of the method I have been using is below.

Animal Interface

Java Code:

public class Animal{
public String serialize();
} mh_sh_highlight_all('java'); Deserializer Interface

[code]....

And when you needed to deserialize:

Java Code:

Deserializer d=AnimalSpecies.getSpeciesDeserializer(serialized.split(AnimalSpecies.DELIMITER)[0]);
if (d!=null){
d.deserialize(serialized);
} mh_sh_highlight_all('java');

What I mean by this is that any serialized Animal must have a way of identifying which animal it is so that it's deserializer can be accessed. This can be worked around by implementing a wrapper that adds this information directly before it is written to a file, and removes it directly before deserialization.

Why not use built in serialization/deserialization? I would like the serialized data to be readable and easily editable.

View Replies View Related

Implementing Heap From ArrayList

Nov 25, 2014

in my class is implement a heap and use some of the methods we were provided. The methods I was provided to code and use are "siftDown", "isEmpty" and "heapify". I'm pretty sure the code I have written for "heapify" and "isEmpty" is correct, where I think I am finding fault is the code for my "siftDown". Would you mind taking a look at my code and see why when adding integers to the heap object that I have created in the main code, that they are not being output correctly?

public class Tester {
public static void main(String[] args) {
Heap myHeap = new Heap();
myHeap.insert(9);
myHeap.insert(15);
myHeap.insert(6);
myHeap.insert(4);
myHeap.insert(10);
myHeap.insert(9);
myHeap.insert(3);

[code]....

View Replies View Related

Implementing Collisions In Frogger

Oct 5, 2014

I am building a frogger game and am having some trouble implementing collisions. I've been going off of various different tutorials and it seems like my frogCollisions function should work based off them, but no matter where I place it collisions aren't registering. Here is the frogCollisions function I am trying to use. I don't think it is very efficient to be checking all of the items in my manager class every loop, but can't think of another way to do this with manager classes. You can see my full code on my github if you would like to see the whole project. It's at: URL....

public void frogCollisions() {
for(int i = 0; i < carManager.smSize(); i++) {
if(f.intersects(carManager.smCars.get(i).getRect())){
player.decreaseLives();
System.out.println(player.getLives());
checkGameOver(); // NEED TO IMPLEMENT STILL

[code]....

View Replies View Related

Program For Implementing A Stack

Jan 3, 2015

I tried to write a program to implement a stack but it has a bug I am unable to solve.The bug is that whenever I choose an operation to perform, eg push, After performing the operation, the loop is executed once again and Invalid choice message appears, i.e. the default case. And then the loop again executes to choose further option. Here is my code

class Stack {
private char[] stck;
private int len;
private int top;

[code]....

View Replies View Related

Implementing Inheritance In Java

Apr 25, 2014

i was leaning inheritance and tried to implement it in Java.This is my base class vehicl.java

public class vehicle{
private int topSpeed;
private int cubicCap;
private String modelName;
private boolean hasAlloy;

[code]...

I also have a derived class called car.java.What i wanted to do in the derived class was that i wanted to override the constructor as well as the getInfo() method from the base class.I wanted to add an additional attribute to the car "numberSeats" and display tat too when the object to car class calls the getInfo() method .It showed an error "identifier required" when i tried to compile car.java program.

import java.util.Scanner;
public class car extends vehicle{
//int numberSeats;
//System.out.println("Enter the number of Seats");
Scanner numberSeats=new Scanner(System.in);
numberSeats=numberSeats.nextInt();
//System.out.println(numberSeats.nextInt());

[code]....

explain the errors that i get when i tried to compile car.java without using super keyword or without defining the constructor from the Car class ?

View Replies View Related

Swing/AWT/SWT :: Implementing Listener Of GUI In A Different Class?

Jun 26, 2014

I have two different classes called Login (in the package View) and RegButtonListener (in the package Controller). I want to use the MVC pattern.

Login creates a GUI for login. I used NetBeans GUI Builder to create it.

In the class RegButtonListener there is the code for the click of the buttons, then various listeners of the GUI.

Now I want to close the login frame at the click of a button so I want to use the dispose() method.

If I had all the code (GUI code and code of the listener) in the same file, close the frame would be easy enough to do because this.dispose(). But in my case I have two different classes.

I also have a second problem.

In Login class (in the packege View) I have included the line :

regButton.addActionListener(Controller.RegButtonListener).

However, Netbeans tells me an error "package regButton does not exist. <identifier> expected". Why does he consider regButton a package? How can I fix these two problems?

How do I do then?
 
Below is the code of the two classes.

Login class.
public class Login extends javax.swing.JFrame {
/** Creates new form Login */
public Login() {
initComponents();

[code]....

View Replies View Related

Implementing A Thread-safe Queue

Jul 10, 2014

I have situation where a user can request java server to send a value to an embedded device, and if the device is asleep, that value needs to be stored in a queue until the device wakes up and sends a position to java server, at which point the server checks if there is a value in the queue and if there is, it then sends that value to the device. The maximum size of the queue is 1 for now. And if the user makes continuous requests to java server, the old value is removed and the new value is added.

Initially I was looking into BlockingQueue, but the problem with that is, well, it blocks. queue.put(value) will block if queue is full, and queue.take() will block if queue is empty. I can't have something that blocks. When the device responds to server, server checks if value is in queue, if it is not then the server carries on the rest of its responsibility. Thus, I then entertained ConcurrentLinkedQueue. While queue.offer(value) and queue.poll(); allow you to add and remove values respectively from the queue without blocking, it does not allow you to set a maximum size limit of the queue. My queue must have a maximum size limit and it has to always be the newest value the user submits to the queue (where old values are removed).So this is what I came up with:

Java Code: class Unit {
private List<Integer> cmdQueue;

public Unit(){
cmdQueue = Collections.synchronizedList(new LinkedList<Integer>());

[code]....

I use Collections.synchronizedList, as I do here, do I still need to use synchronize as I did above?

View Replies View Related







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