why is compareTo(T) taking its argument as Object insted of the the class T that I passed? - comparable

I'm trying to use compareTo() in my class but it keeps giving me this error :
The method compareTo(T) in the type Comparable<T> is not applicable for the arguments (Object)
although a simple casting can fix this error and the code will run fine, I want to now the right way to do it
public class BinarySearchTreeImpl<T extends Comparable<T>> implements BinarySearchTree<T>, Iterable{
private Node root;
#Override
public boolean isEmpty() {
return this.root == null;
}
#Override
public boolean insert(T item) throws DuplicateItemException {
Node newNode = new Node(item);
if(isEmpty()){
this.root = newNode;
return true;
}
else{
Node current = this.root;
while(current != null){
if(item.compareTo(current.item) == -1 ){ // The method compareTo(T) in the type Comparable<T> is not applicable for the arguments (Object)
.
.
.
public class Node<T>{
T item;
Node leftChild;
Node rightChild;
public Node(T item){
this.item = item;
}
.
.
.
If I changed the Node class to Node<T extends Comparable<T> I get almost the same error
The method compareTo(T) in the type Comparable<T> is not applicable for the arguments (Comparable)

Related

How to pop to root

I am writing a WPF application with MvvmCross. I have a custom view presenter that I want to use so that I can pop multiple view models in 1 shot. Here is my view presenter:
public class ViewPresenter : MvxWpfViewPresenter
{
ContentControl _contentControl;
Type _currentViewModelType;
IMvxViewModel _rootViewModel;
public ViewPresenter(ContentControl c) : base(c)
{
_contentControl = c;
AddPresentationHintHandler<SetRootHint>(SetRootHintHandler);
AddPresentationHintHandler<PopToRootHint>(PopToRootHintHandler);
}
protected override void ShowContentView(FrameworkElement element, MvxContentPresentationAttribute attribute, MvxViewModelRequest request)
{
base.ShowContentView(element, attribute, request);
_currentViewModelType = request.ViewModelType;
}
private bool SetRootHintHandler(SetRootHint hint)
{
_rootViewModel = hint.CurrentViewModel;
return true;
}
private bool PopToRootHintHandler(PopToRootHint hint)
{
// How to pop all the way down to _rootViewModel ?
return true;
}
}
How can I pop all the way back to _rootViewModel? Is there a better way of popping back multiple view models in one shot?
I ended up writing a helper class that keeps a reference of all the view models, as well as the one you set as the Root. And then I can just call my PopToRoot method.
public class NavigationStack
{
private readonly List<IMvxViewModel> _stack;
public IMvxViewModel Root { get; set; }
public NavigationStack()
{
_stack = new List<IMvxViewModel>();
}
public void AddToStack(IMvxViewModel viewModel)
{
_stack.Add(viewModel);
}
public async Task PopToRoot(IMvxNavigationService navigationService)
{
if (Root == null)
{
throw new Exception("Can not pop to root because Root is null.");
}
else
{
_stack.Reverse();
foreach (var v in _stack)
{
if (v != Root)
{
await navigationService.Close(v);
}
else
{
break;
}
}
_stack.Clear();
}
}
}
It works, but I'm not sure if this is a good idea since I'm keeping a reference to all the IMvxViewModel in my app, and closing them one after another...does anyone know if this code can cause any problems in the framework?

How to sort the following objects accordingly? (Array, ArrayList, Comparable)

I finally understood the various possibilities of Comparable from java.util.Collections;
I can order an object, for example "Beer" with attributes float content, String name and String origin in any order that I want, combining them how I want.
Now the question:
I have the following classes (code provided last):
Building()
Address();
Building can be one of three types, for example Dwelling, House, Bungalow.
Now, task is "to sort all buildings, first by the city (ascending), second by the street (ascending) and then by the street number (ascending).
Normally I would simply sort the list first by city, then by street and then by number. Of course after the first sort its solution would get mixed up by the following sorts.
Thats why I searched the net and found Comparable.
Thing is: It did work with the beer example, but does not with the address. Cause it is implemented as an ArrayList, and as I found out, it just works for Arrays.
But even if it did, the Addresses themselves are not an Array, but part of the Object Building.
So how on god's earth is one supposed to solved this?
I think I spent more than 8 hours with this cr*p, and the students are supposed to solve similiar issues within 2 - 3 hours.
Any suggestions are appreciated.
Thanks,
Neo
import java.util.List;
public abstract class Building {
private Address address;
private List<Owner> owners;
public abstract double getCostRate(double costs);
public void setAddress(Address address) {
this.address = address;
}
public Address getAddress() {
return address;
}
public List<Owner> getOwners() {
return owners;
}
}
Class Address:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import de.uni_mannheim.informatik.swt.pm.extended.ComparatorCityStreetNumber;
public class Address implements Comparable<Address> {
private String street;
private int houseNr;
private int zip;
private String city;
private String country;
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public int getZip() {
return zip;
}
public void setZip(int zip) {
this.zip = zip;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public void setHouseNr(int houseNr) {
this.houseNr = houseNr;
}
public int getHouseNr() {
return houseNr;
}
/**
* eclipse is able to generate the equals method automatically ;)
*/
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Address other = (Address) obj;
if (city == null) {
if (other.city != null)
return false;
} else if (!city.equals(other.city))
return false;
if (country == null) {
if (other.country != null)
return false;
} else if (!country.equals(other.country))
return false;
if (houseNr != other.houseNr)
return false;
if (street == null) {
if (other.street != null)
return false;
} else if (!street.equals(other.street))
return false;
if (zip != other.zip)
return false;
return true;
}
Comparator:
public class ComparatorCityStreetNumber implements Comparator<Address> {
public int compare(Address a1, Address a2) {
if (a1.getCity().compareTo(a2.getCity()) == 0) {
if (a1.getStreet().compareTo(a2.getStreet()) == 0) {
if (a1.getHouseNr() > a2.getHouseNr()) {
return -1;
} else {
return a1.getStreet().compareTo(a2.getStreet());
}
} else if (a1.getCity().compareTo(a2.getCity()) > 0) {
return -1;
} else {
return 1;
}
}
return 0;
}
}
It looks like your Building is an abstract class, which gives you a hint that you must extend it.
Given that this is an assignment, I'm not going to do it for you. Instead, I will give you some pointers :-)
Create a Property object which extends Building, and implement the getCostRate method which returns zero for now. Either that, or make Building concrete.. My guess is that subclasses of Building are yet to come, so if that's the case, scratch that idea.
Now create a PropertyComparator implementation of the Comparator object.
Now, from the perspective of being able to determine your sort criteria, you should be able to write the simple logic to compare one Property with another Property, and their corresponding Addresses - if you want to go for gold, create an AddressComparator too - and make your BuildingComparator call the AddressComparator to compare the addresses.
Finally, if you have a collection of Property objects, put them into a TreeSet, but construct the TreeSet with your PropertyComparator.
Once it's in the TreeSet, it will be ordered according to your implementation.
Good luck!
I found my mistake, it was in the last equasion. IF must not be this.getCity().compareTo(address.getCity()) = 0 but correctly has to be this.getCity().compareTo(address.getCity()) > 0
So, the whole code to sort after my criteria looks like this:
public int compareTo(Address address) {
if (this.getCity().compareTo(address.getCity()) == 0) {
if (this.getStreet().compareTo(address.getStreet()) == 0) {
if (this.getHouseNr() > address.getHouseNr()) {
return 1;
} else {
return -1;
} // end house number
} else {
return this.getStreet().compareTo(address.getStreet());
} //end street
} else if (this.getCity().compareTo(address.getCity()) > 0) {
return 1;
} else {
return -1;
} //end city
}
You just need to implement compareTo(...) method and there is where you should put the Address comparison logic, that will be used when you call Collections.sort(...) method for a List<Address>object.
Example:
List<Address> l = new ArrayList<Address>();
// ... fill values in the list
Collections.sort(l);
This will use the logic from your compareTo(...) method in Address class. For example:
int compareTo(Address o) {
return o.getCity().compareTo(this.getCity());
}
So this would be using the String implementation of compareTo(...) method for sorting the Addresses by city. And in this way you don't need to use the ComparatorCityStreetNumber class nor any other Comparator class.
For more information:
http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html#compareTo(T)
EDIT:
If your compareTo(...) method doesn't work you can always place this logic in the compare(Address a1, Address a2) method in your ComparatorCityStreetNumber class.
Then you don't need to implement Comparable anymore in your Address class nor implement compareTo(...) method there.
And then your sort call would be:
List<Address> l = new ArrayList<Address>();
// fill in the list with addresses
ComparatorCityStreetNumber c = new ComparatorCityStreetNumber();
Collections.sort(l, c);
So please try this and edit your question with your new output if you have other problems there.
For more information: http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html#compare(T, T)

Advice in modeling Datastore Entities with Objectify

I just started with the Datastore and Objectify (complete newbie) and I am seeking for a bit of advice before modelling my entities.
I am developing some kind of stock trading application where the users can track stocks by defining the stock id, target price and condition (lower or higher price than the target).
The application fetches the stocks from an external website and keeps them in an array. It then needs to check which StockTracking is matching those Stocks prices kept in the array.
The StockTracking has this structure:
StockCode, TargetPrice, Condition (lower or higher)
What I want to do is something like:
for (Stock in stockArray) {
SELECT * FROM StockTracking WHERE StockCode = stock.code AND
((Condition = 'Lower' AND TargetPrice <= Stock.price) OR
(Condition = 'Higher' AND TargetPrice >= Stock.price))
}
I need some help in determining how and which indexes should be created to be able to query like this. Also, although the number of stocks is fixed and not that big (under 50) I wonder if there's a way to perform this functionality in a more optimal way (ie. lower query times).
Thanks in advance
Below is a Generic DAO Class from one of my work, where I have implemented almost all basic queries in Objectify. It is actually a Generic Implementation of basic Objectify functions using Template Classes.
package com.myweb.common.dao;
import static com.googlecode.objectify.ObjectifyService.ofy;
import java.util.List;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.ObjectifyService;
import com.myweb.common.exception.DatabaseException;
import com.myweb.model.User;
public abstract class AbstractGenericDaoImpl implements GenericDao{
static {
ObjectifyService.register(User.class);
}
#Override
public <T> void create(T t) {
ofy().save().entity(t).now();
}
#Override
public <T> String createWithKey(T t) {
Key<T> key = ofy().save().entity(t).now();
return key.getString();
}
#Override
public <T> Long createWithID(T t) {
Key<T> key = ofy().save().entity(t).now();
return key.getId();
}
#Override
public <T> void update(Class<T> clazz, Long id, T t) throws DatabaseException {
if (id == null) {
throw new DatabaseException("ID cannot be null");
}
T tnew = ofy().load().type(clazz).id(id).get();
ofy().save().entity(tnew).now();
}
#Override
public <T> void update(Class<T> clazz, String key, T t) throws DatabaseException {
if (key == null) {
throw new DatabaseException("ID cannot be null");
}
T tnew = ofy().load().type(clazz).id(key).get();
ofy().save().entity(tnew).now();
}
#Override
public <T> T getById(Class<T> clazz, Long id) throws DatabaseException {
if (id == null) {
throw new DatabaseException("ID cannot be null");
}
return ofy().load().type(clazz).id(id).get();
}
#Override
public <T> T getByKey(Class<T> clazz, String key) throws DatabaseException {
if (key == null) {
throw new DatabaseException("ID cannot be null");
}
return ofy().load().type(clazz).id(key).get();
}
#Override
public <T> List<T> list(Class<T> clazz) {
List<T> list = ofy().load().type(clazz).list();
return list;
}
#Override
public <T> void delete(Class<T> clazz, Long id) throws DatabaseException {
if (id == null) {
throw new DatabaseException("ID cannot be null");
}
T t = ofy().load().type(clazz).id(id).get();
if(t != null){
ofy().delete().entity(t).now();
}
}
#Override
public <T> void deleteByKey(Class<T> clazz, String key) throws DatabaseException {
if (key == null) {
throw new DatabaseException("ID cannot be null");
}
T t = ofy().load().type(clazz).id(key).get();
if(t != null){
ofy().delete().entity(t).now();
}
}
}
Below is a method which uses filter query example in Objectify.
public User getUserByEmail(String email) {
return ofy().load().type(User.class).filter("email", email).first().get();
}
Listing fields with Filter
public List<User> getUsers(String f1, String f2) {
return ofy().load().type(User.class).filter("f1", f1).filter("f2", f2).list();
}

How to get path from TreeSelectionListener

Here is my problem. I would like to write a primitive MultiRenameTool (the rename part is not important yet).
You could browse the directories on the left side (JTree), and when you select one, you could see its content on the right side (JTable - just the files).
The problem is, that I can't figure out how to pass the the selected directory to the JTable's list.
I've used the code of Kirill Grouchnikov for the JTree and I slighty modified it.
import java.awt.BorderLayout;
import java.awt.Component;
import java.io.File;
import java.io.FileFilter;
import java.util.*;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.filechooser.FileSystemView;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
/**
* #author Kirill Grouchnikov
*/
public class FileTreePanel extends JPanel {
protected static FileSystemView fsv = FileSystemView.getFileSystemView();
private JTree tree;
//At first I was trying this - but it is wrong.
public static File current;
private static class FileTreeCellRenderer extends DefaultTreeCellRenderer {
private Map<String, Icon> iconCache = new HashMap<String, Icon>();
private Map<File, String> rootNameCache = new HashMap<File, String>();
#Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
FileTreeNode ftn = (FileTreeNode) value;
File file = ftn.file;
String filename = "";
if (file != null) {
if (ftn.isFileSystemRoot) {
filename = this.rootNameCache.get(file);
if (filename == null) {
filename = fsv.getSystemDisplayName(file);
this.rootNameCache.put(file, filename);
}
} else {
filename = file.getName();
}
}
JLabel result = (JLabel) super.getTreeCellRendererComponent(tree, filename, sel, expanded, leaf, row, hasFocus);
if (file != null) {
Icon icon = this.iconCache.get(filename);
if (icon == null) {
icon = fsv.getSystemIcon(file);
this.iconCache.put(filename, icon);
}
result.setIcon(icon);
}
return result;
}
}
private static class FileTreeNode implements TreeNode {
private File file;
private File[] children;
private TreeNode parent;
private boolean isFileSystemRoot;
public FileTreeNode(File file, boolean isFileSystemRoot, TreeNode parent) {
this.file = file;
this.isFileSystemRoot = isFileSystemRoot;
this.parent = parent;
this.children = this.file.listFiles(new FileFilter() {
//!Modification here - display only the directories
#Override
public boolean accept(File file) {
return file.isDirectory();
}
});
if (this.children == null) {
this.children = new File[0];
}
//obliviously wrong "solution" :(
current = file;
}
public FileTreeNode(File[] children) {
this.file = null;
this.parent = null;
this.children = children;
}
#Override
public Enumeration<?> children() {
final int elementCount = this.children.length;
return new Enumeration<File>() {
int count = 0;
#Override
public boolean hasMoreElements() {
return this.count < elementCount;
}
#Override
public File nextElement() {
if (this.count < elementCount) {
return FileTreeNode.this.children[this.count++];
}
throw new NoSuchElementException("Nincs több elem.");
}
};
}
#Override
public boolean getAllowsChildren() {
return true;
}
#Override
public TreeNode getChildAt(int childIndex) {
return new FileTreeNode(this.children[childIndex],
this.parent == null, this);
}
#Override
public int getChildCount() {
return this.children.length;
}
#Override
public int getIndex(TreeNode node) {
FileTreeNode ftn = (FileTreeNode) node;
for (int i = 0; i < this.children.length; i++) {
if (ftn.file.equals(this.children[i])) {
return i;
}
}
return -1;
}
#Override
public TreeNode getParent() {
return this.parent;
}
#Override
public boolean isLeaf() {
return (this.getChildCount() == 0);
}
}
public FileTreePanel() {
super();
this.setLayout(new BorderLayout());
File[] roots = File.listRoots();
FileTreeNode rootTreeNode = new FileTreeNode(roots);
this.tree = new JTree(rootTreeNode);
this.tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
this.tree.setCellRenderer(new FileTreeCellRenderer());
this.tree.setRootVisible(true);
this.tree.addTreeSelectionListener(new JTreeSelectionListener());
JScrollPane jsp = new JScrollPane(this.tree);
this.add(jsp, BorderLayout.CENTER);
}
private class JTreeSelectionListener implements TreeSelectionListener {
#Override
public void valueChanged(TreeSelectionEvent jtsl) {
TreePath o = jtsl.getPath();
System.out.println(o);
System.out.println(current);
SelectionList.listBuilder(current);
}
}
}
The most important part is at the end, at the TreeSelectionEvent. Here somehow I should be able to convert/make/cast a File from the actually selected Directory.
import java.awt.BorderLayout;
import java.awt.Color;
import java.io.File;
import java.io.FileFilter;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class SelectionList extends JPanel {
private static FilesData data;
private static JTable table;
public SelectionList() {
super();
data = new FilesData();
table = new JTable(data);
table.setFillsViewportHeight(true);
table.setShowGrid(true);
table.setGridColor(Color.BLACK);
JScrollPane jsp = new JScrollPane(table);
this.add(jsp, BorderLayout.CENTER);
}
public static void listBuilder(final File f) {
data.files.clear();
File[] fs = f.listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
return file.isFile();
}
});
if (fs != null) {
for (File m : fs) {
Files ujFile = new Files(m, m.isHidden(), Menu.checkAll.getState());
if (!m.isHidden() || Menu.hiddenFilesVisibility.getState()) {
data.files.add(ujFile);
}
}
}
table.repaint();
}
}
It is interesting because of the listBuilder function. I think it is enough information, but if you need my other classes too, I will upload it. I appreciate any help! Thank you all in avance. Anyone? :(
The following snippet shows how you may get the file from the path inside valueChanged:
public void valueChanged(TreeSelectionEvent jtsl) {
TreePath path = jtsl.getPath();
FileTreeNode filenode = (FileTreeNode) path.getLastPathComponent();
File file = filenode.file;
...
}

Passing a list or array to RESTeasy using get

I've seen this kind of thing described in various examples showing how to create a REST service which takes arrays or a list of objects as part of the URL.
My question is, how to implement this using RESTeasy?
Something like the following would be how i would assume this to work.
#GET
#Path("/stuff/")
#Produces("application/json")
public StuffResponse getStuffByThings(
#QueryParam("things") List<Thing> things);
Create a StringConverter and a use a wrapper object. Here is a quick and dirty example:
public class QueryParamAsListTest {
public static class Thing {
String value;
Thing(String value){ this.value = value; }
}
public static class ManyThings {
List<Thing> things = new ArrayList<Thing>();
ManyThings(String values){
for(String value : values.split(",")){
things.add(new Thing(value));
}
}
}
static class Converter implements StringConverter<ManyThings> {
public ManyThings fromString(String str) {
return new ManyThings(str);
}
public String toString(ManyThings value) {
//TODO: implement
return value.toString();
}
}
#Path("/")
public static class Service {
#GET
#Path("/stuff/")
public int getStuffByThings(
#QueryParam("things") ManyThings things){
return things.things.size();
}
}
#Test
public void test() throws Exception {
Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
dispatcher.getProviderFactory().addStringConverter(new Converter());
dispatcher.getRegistry().addSingletonResource(new Service());
MockHttpRequest request = MockHttpRequest.get("/stuff?things=a,b,c");
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
Assert.assertEquals("3", response.getContentAsString());
}
}
I think you can also use a StringParamUnmarshaller
I had some luck with this, using Collection rather than List. I was unable to make a StringConverter for List work.
#Provider
public class CollectionConverter implements StringConverter<Collection<String>> {
public Collection<String> fromString(String string) {
if (string == null) {
return Collections.emptyList();
}
return Arrays.asList(string.split(","));
}
public String toString(Collection<String> values) {
final StringBuilder sb = new StringBuilder();
boolean first = true;
for (String value : values) {
if (first) {
first = false;
} else {
sb.append(",");
}
sb.append(value);
}
return sb.toString();
}
}
I did the toString from my head. Be sure to write unit tests for it to verify. But of course, everything is easier and clearer when you use Guava. Can use Joiner and Splitter. Really handy.
Just use a wrapper on its own, no need for anything else.
In your endpoint
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
#Path("/find")
#GET
MyResponse find(#QueryParam("ids") Wrapper ids);
And you wrapper looks like this :
public class Wrapper implements Serializable {
private List<BigInteger> ids = Collections.emptyList();
public String toString() {
return Joiner.on(",")
.join(ids);
}
public List<BigInteger> get() {
return ids;
}
public Wrapper(String s) {
if (s == null) {
ids = Collections.emptyList();
}
Iterable<String> splitted = Splitter.on(',')
.split(s);
Iterable<BigInteger> ids = Iterables.transform(splitted, Functionz.stringToBigInteger);
this.ids = Lists.newArrayList(ids);
}
public Wrapper(List<BigInteger> ids) {
this.ids = ids;
}
}

Resources