This code compares awt rectangles by surface area but I am getting an error when I use collections.sort. I want it to output a sorted ArrayList of awt rectangles based on their surface area.
surface area = width * height.
I have created a sorting class and extended the comparable interface and I am calling/invoking this class as a parameter in Collections.sort(rectangleList, new SortBySurfaceArea());, however when I put a cursor over collections.sort, I get this pop-up error.
no suitable method found for sort(List<Rectangle>,SortBySurfaceArea)
method Collections.<T#1>sort(List<T#1>) is not applicable
(cannot infer type-variable(s) T#1
(actual and formal argument lists differ in length))
method Collections.<T#2>sort(List<T#2>,Comparator<? super T#2>) is not applicable
(cannot infer type-variable(s) T#2
(argument mismatch; SortBySurfaceArea cannot be converted to Comparator<? super T#2>))
where T#1,T#2 are type-variables:
T#1 extends Comparable<? super T#1> declared in method <T#1>sort(List<T#1>)
T#2 extends Object declared in method <T#2>sort(List<T#2>,Comparator<? super T#2>)
(Alt-Enter shows hints)
Code listing follows:
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author HP
*/
public class RectangleSurfaceAreaComparable {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Rectangle rectangle_0 = new Rectangle(50, 4);
Rectangle rectangle_1 = new Rectangle(80, 3);
Rectangle rectangle_2 = new Rectangle(90, 2);
System.out.println(surfaceArea(rectangle_0.getWidth(), rectangle_0.getHeight()));
List<Rectangle> rectangleList = new ArrayList<>();
rectangleList.add(rectangle_0);
rectangleList.add(rectangle_1);
rectangleList.add(rectangle_2);
for (Rectangle rectangle : rectangleList) {
System.out.println("" + rectangle);
}
Collections.sort(rectangleList, new SortBySurfaceArea());
for (Rectangle rectangle : rectangleList) {
System.out.println("" + rectangle);
}
}
/**
*
* #param width
* #param height
* #return
*/
public static double surfaceArea(double width, double height) {
double sa = width * height;
return sa;
}
}
SortBySurfaceArea.java
import java.awt.Rectangle;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author HP
*/
public class SortBySurfaceArea implements Comparable<Rectangle> {
#Override
public int compareTo(Rectangle o) {
return (o.height * o.width);
}
}
Collections.sort needs a Comparator, not a Comparable, so your SortBySurfaceArea could be:
import java.awt.Rectangle;
import java.util.Comparator;
public class SortBySurfaceArea implements Comparator<Rectangle>
{
public int compare(Rectangle o1, Rectangle o2)
{ return o1.height*o1.width-o2.height*o2.width; }
}
No I want to use comparable
How about this? (You might want to call SortBySurfaceArea differently, e. g. SortableRectangle.)
import java.awt.Rectangle;
public class SortBySurfaceArea extends Rectangle implements Comparable<Rectangle>
{
public SortBySurfaceArea(Rectangle r) { super(r); }
public int compareTo(Rectangle o) { return height*width-o.height*o.width; }
}
…
List<SortBySurfaceArea> rectangleList = new ArrayList<>();
rectangleList.add(new SortBySurfaceArea(rectangle_0));
rectangleList.add(new SortBySurfaceArea(rectangle_1));
rectangleList.add(new SortBySurfaceArea(rectangle_2));
…
Collections.sort(rectangleList);
Related
I have the following Spring Bean structure:
public abstract class XmlBaseChild {
protected Integer value;
protected String text;
#Autowired
transient protected MasterCodeService masterCodeService;
public XmlBaseChild(Integer value) {
setValue(value);
}
/**
* Set the Numeric value of the ChildView.
* This code is common for all childViews and handles a null value.
* #param value Numeric value of the ChildView
*/
#JsonProperty(value="id")
public void setValue(Integer value) {
if (value == null) {
this.value = null;
this.text = null;
return;
}
setConcreteValue(value);
}
/**
* Set the Numeric value of the ChildView.
* This code must be overridden by the concrete childViews.
* #param value Numeric value of the ChildView
*/
protected void setConcreteValue(Integer value){
boolean keyNotFound = true;
if (value != null && value > -1) {
this.value = value;
String messageKey = getValueFromMap(value, GetMasterCodeMapForChildView());
if (messageKey != null) {
this.text = LocalizeString(messageKey, null, getLocale);
keyNotFound = false;
}
}
if (keyNotFound){
throw new NotFoundException();
}
}
protected abstract Map<String, MasterCodeView> GetMasterCodeMapForChildView();
}
And the subclass:
#Component
#XmlRootElement(name=XmlDeployTool.VIEW_NAME)
public class XmlDeployTool extends XmlBaseChild {
public static Map<String, MasterCodeView> toolTypeCodes = new HashMap<String, MasterCodeView>();
/**
* Constructor for creating this object and preparing for marchalling (from java objects to xml/json).
* #param value Numeric value of the ChildView
* #param request HttpServletRequest
* #param includeSelf Include SELF link
* #param includeUP Include UP link
*/
public XmlDeployTool(Integer value) {
super(value);
}
/**
* Initialize the Tool Type codes after the component is wired (postconstruct),
* so that they are available in the constructor when an XmlDeploy object is created.
*/
#PostConstruct
protected void initializeDeployToolTypeCodes() {
toolTypeCodes = convertListToMap(masterCodeService.getToolTypeCodes());
}
#Override
protected Map<String, MasterCodeView> GetMasterCodeMapForChildView() {
return toolTypeCodes;
}
}
However, from what I understand from other posts like Order of #PostConstruct and inheritance, the #PostConstruct here normally executes AFTER the constructor is called. Then why is the toolTypeCodes map populated during the constructor? Is this part of the #Component annotation of Spring?
I also tried doing this with the masterCodeView map defined in the XmlBaseChild and only the PostConstruct method defined in the XmlDeployTool class, but that didn't work, the list didn't get initialized in that case. Why is this?
After checking the documentation and reading up some more, I figured out what's going on here:
Because my subclass is annotated with #Component, the PostConstruct triggers as part of the Spring startup process, even before any invocations of the normal constructor. Because of this, the static Map with MasterCodeViews gets populated, and since this is static, it stays populated as part of the subclass static properties. Because of this, this map has the proper usable data during construction.
When I tried to move the Map to the base class, In effect I turned this from a static property of the subclass to a static property of the subclass, which meant each constructor in turn populated it with the separate properties, leading to the map having the wrong data most of the time. When after that I tried to do this with a non-static map, the data wasn't retained when I invoked the constructor from code because this was effectively a new object with no initialized components.
I'm migrating my Guava Functions and Predicates to Java 8. Unparameterized Predictates are easy, I just change from class to interface and put a "default" in front of the apply() method. What I'm stuck on is parameterized Predicates. How can I define a reusable parameterized predicate in Java 8. Here's my current Guava code:
import com.google.common.base.Predicate
public class InSectorPredicate implements Predicate<Unit> {
private final SectorCoords coords;
public InSectorPredicate(SectorCoords coords) {
this.coords = coords;
}
#Override
public boolean apply(Unit unit) {
return unit.getCoords().equals(coords);
}
}
Interfaces can't maintain state. The issue is the coords parameter.
But it doesn't need to be an interface? you can simply use a class like you already have been. Or hell, while you are in a migration state, just continue to use the Guava Predicates as the type signature of Guava's Predicate is
public interface Predicate<T> extends java.util.function.Predicate<T> So they will continue to work on Java 8
From the JD of Guava's Predicate:
* <p>As this interface extends {#code java.util.function.Predicate}, an instance of this type may
* be used as a {#code Predicate} directly. To use a {#code java.util.function.Predicate} where a
* {#code com.google.common.base.Predicate} is expected, use the method reference {#code
* predicate::test}.
Example code, if you want to port.
public class InSectorPredicate8 implements java.util.function.Predicate<Unit> {
private final SectorCoords coords;
public InSectorPredicate8(SectorCoords coords) {
this.coords = coords;
}
#Override
public boolean test(Unit unit) {
return unit.getCoords().equals(coords);
}
}
But depending on exact usage, most of the time where you would construct the InSectorPredicate, you could simply, do
Predicate<Unit> InSectorPredicate = new InSectorPredicate(coords);
migrates to
Predicate<Unit> InSectorPredicate = (Unit unit) -> unit.getCoords().equals(coords);
Changing apply to test doesn't work?
and obviously replace import com.google.common.base.Predicate; with import java.util.function.Predicate;
I have an enum which implements an interface. The method is implemented in its constants with a comment for each method:
public interface MyIF{
int foo1();
}
public enum SomeTypes implements MyIF{
TYPE_ONE {
/**
* this method ...
*
* #return ...
*/
#Override
public int foo1() {...}
}, ...
}
Javadoc ignores the method comment. Everything else is generated fine. Is there a way I can make these comments appear in the generated javadoc ?
Thanks
I have a class Abc with method (body is not important):
/**
* #return SomeBaseClass
*/
function getAll() { ... }
In child class of Abc called AbcChild I'd like to redefine only type of returning class to see it properly in Netbeans. Can I do it without redefining method:
/**
* #return SomeClass
*/
function getAll() { return parent::getAll(); }
Try something like this:
/**
* #method SomeClass getAll()
*/
class AbcChild
{
// ....
}
More info about #method
No, because you need the child method code itself in order to have a child docblock to associate with it. If you have the docblock but not the method code, the docblock won't be tied to anything, and thus will have no effect. Most people dislike altering their code to accommodate docblock behavior, though it's never really bothered me to do so.
However, another option for you is to adjust the #return tag on the parent method, so that it lists all possible return types that you want to indicate the children could return. That makes me wonder, though... if you are not actually overriding the method itself, then how is the child class actually returning a different class than the parent? I can see ways to do this in my mind, involving class properties that contain the differing class objects, but they'd feel like code smells to me ;-)
If there is no method override code itself in the child, then I would choose to put all possible return types in the parent's #return.
Actually I think there is other way than full method override. You can change #return phpdoc block in the child interface which extends base interface. Let me explain with code what I mean:
interface EntityRepository
{
/**
* #return object
*/
public function get($id);
public function add($entity, $sync = false);
public function remove($entity, $sync = false);
// other methods common for custom repositories
}
interface ProjectRepository extends EntityRepository
{
/**
* #return Project
*/
public function get($id);
}
This is part of your domain. And now the concrete implementation taken from Symfony & Doctrine:
use Doctrine\ORM\EntityRepository;
use Model\Repository\EntityRepository as BaseEntityRepository;
abstract class DoctrineEntityRepository extends EntityRepository implements BaseEntityRepository
{
public function get($id)
{
$entity = $this->find($id);
if (!$entity) {
throw new EntityNotFoundException();
}
return $entity;
}
public function add($entity, $sync = false)
{
// method implementation
}
public function remove($entity, $sync = false)
{
// method implementation
}
}
use Model\Repository\ProjectRepository as BaseProjectRepository;
class ProjectRepository extends DoctrineEntityRepository implements BaseProjectRepository
{
public function specificQueryForProjects()
{
// method implementation
}
}
This way you dont have to override methods in child classes only because of code autocomplete. You just have to extend interfaces to let users of your API know that the return value changed.
I'm trying to use another way of pagination in PrimeFaces' DataTable.
What I want to do is that new pages are shown "vertically", so the new loaded data has to be appended at the end of the previous DataTable.
Something like Facebook's home stream, in which clicking "Load old posts" will make them appear under the newest one.
Is this possible??
I've tried almost everything using paginator, but seems like there's no way to build a "vertical" dataTable.
If not with PrimeFaces, is there any component that does what I need?
The loading should be lazy, so, everytime that the user decides to load the new data, a query must be executed. No lists or something!
Thanks :)
EDIT:
JSF Page
<pou:dataTable scrollable="true" liveScroll="true" scrollHeight="400" scrollRows="100" value="#{postListBean_1.posts}" var="post">
<pou:column>
#{post.testo}
<hr/>
</pou:column>
</pou:dataTable>
BEAN
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ManagedBeans;
import ejb.PostManagerLocal;
import entity.Post;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
/**
* La classe si occupa di gestire lo scambio di messaggi tra utenti. Da
* implementare ancora i metodi per l'invio e per la segnalazione dell'avvenuta
* lettura.
*
* #author stefano
*/
#ManagedBean
#RequestScoped
public class PostListBean_1 implements Serializable {
#EJB
private PostManagerLocal postManager;
private List<Post> posts;
private int limit = 0;
/**
* Get the value of posts
*
* #return the value of posts
*/
public List<Post> getPosts() {
limit+=4;
makePosts();
return posts;
}
/**
* Set the value of posts
*
* #param posts new value of posts
*/
public void setPosts(List<Post> posts) {
this.posts = posts;
}
/**
* Creates a new instance of PostListBean
*/
public PostListBean_1() {
}
/**
* Inizializza la lista dei posts, prendendoli in ordine inverso, in modo da
* avere prima i più recenti
*/
#PostConstruct
public void makePosts() {
int[] range = {0, limit};
posts = postManager.findRangeReverse(range);
}
}