Search Results

Search found 196 results on 8 pages for 'compareto'.

Page 3/8 | < Previous Page | 1 2 3 4 5 6 7 8  | Next Page >

  • Factorising program not working. Help required.

    - by Ender
    I am working on a factorisation problem using Fermat's Factorization and for small numbers it is working well. I've been able to calculate the factors (getting the answers from Wolfram Alpha) for small numbers, like the one on the Wikipedia page (5959). Just when I thought I had the problem licked I soon realised that my program was not working when it came to larger numbers. The program follows through the examples from the Wikipedia page, printing out the values a, b, a2 and b2; the results printed for large numbers are not correct. I've followed the pseudocode provided on the Wikipedia page, but am struggling to understand where to go next. Along with the Wikipedia page I have been following this guide. Once again, as my Math knowledge is pretty poor I cannot follow what I need to do next. The code I am using so far is as follows: import java.math.BigInteger; /** * * @author AlexT */ public class Fermat { private BigInteger a, b; private BigInteger b2; private static final BigInteger TWO = BigInteger.valueOf(2); public void fermat(BigInteger N) { // floor(sqrt(N)) BigInteger tmp = getIntSqrt(N); // a <- ceil(sqrt(N)) a = tmp.add(BigInteger.ONE); // b2 <- a*a-N b2 = (a.multiply(a)).subtract(N); final int bitLength = N.bitLength(); BigInteger root = BigInteger.ONE.shiftLeft(bitLength / 2); root = root.add(b2.divide(root)).divide(TWO); // while b2 not square root while(!(isSqrt(b2, root))) { // a <- a + 1 a = a.add(BigInteger.ONE); // b2 <- (a * a) - N b2 = (a.multiply(a)).subtract(N); root = root.add(b2.divide(root)).divide(TWO); } b = getIntSqrt(b2); BigInteger a2 = a.pow(2); // Wrong BigInteger sum = (a.subtract(b)).multiply((a.add(b))); //if(sum.compareTo(N) == 0) { System.out.println("A: " + a + "\nB: " + b); System.out.println("A^2: " + a2 + "\nB^2: " + b2); //} } /** * Is the number provided a perfect Square Root? * @param n * @param root * @return */ private static boolean isSqrt(BigInteger n, BigInteger root) { final BigInteger lowerBound = root.pow(2); final BigInteger upperBound = root.add(BigInteger.ONE).pow(2); return lowerBound.compareTo(n) <= 0 && n.compareTo(upperBound) < 0; } public BigInteger getIntSqrt(BigInteger x) { // It returns s where s^2 < x < (s+1)^2 BigInteger s; // final result BigInteger currentRes = BigInteger.valueOf(0); // init value is 0 BigInteger currentSum = BigInteger.valueOf(0); // init value is 0 BigInteger sum = BigInteger.valueOf(0); String xS = x.toString(); // change input x to a string xS int lengthOfxS = xS.length(); int currentTwoBits; int i=0; // index if(lengthOfxS % 2 != 0) {// if odd length, add a dummy bit xS = "0".concat(xS); // add 0 to the front of string xS lengthOfxS++; } while(i < lengthOfxS){ // go through xS two by two, left to right currentTwoBits = Integer.valueOf(xS.substring(i,i+2)); i += 2; // sum = currentSum*100 + currentTwoBits sum = currentSum.multiply(BigInteger.valueOf(100)); sum = sum.add(BigInteger.valueOf(currentTwoBits)); // subtraction loop do { currentSum = sum; // remember the value before subtract // in next 3 lines, we work out // currentRes = sum - 2*currentRes - 1 sum = sum.subtract(currentRes); // currentRes++ currentRes = currentRes.add(BigInteger.valueOf(1)); sum = sum.subtract(currentRes); } while(sum.compareTo(BigInteger.valueOf(0)) >= 0); // the loop stops when sum < 0 // go one step back currentRes = currentRes.subtract(BigInteger.valueOf(1)); currentRes = currentRes.multiply(BigInteger.valueOf(10)); } s = currentRes.divide(BigInteger.valueOf(10)); // go one step back return s; } /** * @param args the command line arguments */ public static void main(String[] args) { Fermat fermat = new Fermat(); //Works //fermat.fermat(new BigInteger("5959")); // Doesn't Work fermat.fermat(new BigInteger("90283")); } } If anyone can help me out with this problem I'll be eternally grateful.

    Read the article

  • how can I implement Comparable more than once?

    - by codeman73
    I'm upgrading some code to Java 5 and am clearly not understanding something with Generics. I have other classes which implement Comparable once, which I've been able to implement. But now I've got a class which, due to inheritance, ends up trying to implement Comparable for 2 types. Here's my situation: I've got the following classes/interfaces: interface Foo extends Comparable<Foo> interface Bar extends Comparable<Bar> abstract class BarDescription implements Bar class FooBar extends BarDescription implements Foo With this, I get the error 'interface Comparable cannot be implemented more than once with different arguments...' Why can't I have a compareTo(Foo foo) implemented in FooBar, and also a compareTo(Bar) implemented in BarDescription? Isn't this simply method overloading?

    Read the article

  • Squeak - SUnit Testing for Errors

    - by Artium
    I have been suggested to use should:rise in my test case to test for errors that a method might raise. For some reason it does not work as axpected, so I want to verify that I'm doing it right. Here is the code in the test case: self should: [aMyClass compareTo: 'This is a string'] raise: 'invalid input'. My compareTo/1 method looks like this: (aMyClass isKindOf: MyClass) ifFalse: [self error: 'invalid input'.]. The test runner output is that there is "1 errors". Thank you.

    Read the article

  • C# String Operator Overloading

    - by ScottSEA
    G'Day Mates - What is the right way (excluding the argument of whether it is advisable) to overload the string operators <, , <= and = ? I've tried it five ways to Sunday and I get various errors - my best shot was declaring a partial class and overloading from there, but it won't work for some reason. namespace System { public partial class String { public static Boolean operator <(String a, String b) { return a.CompareTo(b) < 0; } public static Boolean operator >(String a, String b) { return a.CompareTo(b) > 0; } } }

    Read the article

  • Lamda expression will not compile

    - by John Soer
    I am very confused I have this lamba expression tvPatientPrecriptionsEntities.Sort((p1, p2) => p1.MedicationStartDate.Value.CompareTo(p2.MedicationStartDate.Value)); Visual studio will not compile it and complains about syntax. I converted the lamba expression to an anonymous delegate as so tvPatientPrecriptionsEntities.Sort( delegate(PatientPrecriptionsEntity p1, PatientPrecriptionsEntity p2) { return p1.MedicationStartDate.Value.CompareTo(p2.MedicationStartDate.Value); } ); and it works fine. The project is uses the .net 3.5 framework and I have a reference to system.linq.

    Read the article

  • Java HashSet is allowing dupes; problem with comparable?

    - by IVR Avenger
    Hi, all. I've got a class, "Accumulator", that implements the Comparable compareTo method, and I'm trying to put these objects into a HashSet. When I add() to the HashSet, I don't see any activity in my compareTo method in the debugger, regardless of where I set my breakpoints. Additionally, when I'm done with the add()s, I see several duplicates within the Set. What am I screwing up, here; why is it not Comparing, and therefore, allowing the dupes? Thanks, IVR Avenger

    Read the article

  • C# - How to implement multiple comparers for an IComparable<T> class?

    - by Gary Willoughby
    I have a class that implements IComparable. public class MyClass : IComparable<MyClass> { public int CompareTo(MyClass c) { return this.whatever.CompareTo(c.whatever); } etc.. } I then can call the sort method of a generic list of my class List<MyClass> c = new List<MyClass>(); //Add stuff, etc. c.Sort(); and have the list sorted according to my comparer. How do i specify further comparers to sort my collection different ways according to the other properties of MyClass in order to let users sort my collection in a number of different ways?

    Read the article

  • How come Java doesn't accept my LinkedList in a Generic, but accepts its own?

    - by master chief
    For a class assignment, we can't use any of the languages bultin types, so I'm stuck with my own list. Anyway, here's the situation: public class CrazyStructure <T extends Comparable<? super T>> { MyLinkedList<MyTree<T>> trees; //error: type parameter MyTree is not within its bound } However: public class CrazyStructure <T extends Comparable<? super T>> { LinkedList<MyTree<T>> trees; } Works. MyTree impleements the Comparable interface, but MyLinkedList doesn't. However, Java's LinkedList doesn't implement it either, according to this. So what's the problem and how do I fix it? MyLinkedList: public class MyLinkedList<T extends Comparable<? super T>> { private class Node<T> { private Node<T> next; private T data; protected Node(); protected Node(final T value); } Node<T> firstNode; public MyLinkedList(); public MyLinkedList(T value); //calls node1.value.compareTo(node2.value) private int compareElements(final Node<T> node1, final Node<T> node2); public void insert(T value); public void remove(T value); } MyTree: public class LeftistTree<T extends Comparable<? super T>> implements Comparable { private class Node<T> { private Node<T> left, right; private T data; private int dist; protected Node(); protected Node(final T value); } private Node<T> root; public LeftistTree(); public LeftistTree(final T value); public Node getRoot(); //calls node1.value.compareTo(node2.value) private int compareElements(final Node node1, final Node node2); private Node<T> merge(Node node1, Node node2); public void insert(final T value); public T extractMin(); public int compareTo(final Object param); }

    Read the article

  • Java: How to make this Serializable?

    - by Hasslarn
    I dont know that much about Serializable, but i need this class to be. How to achieve it? package helpers; public class XY implements Comparable<XY> { public int x; public int y; public XY (int x, int y) { this.x = x; this.y = y; } public int compareTo( XY other ) { String compare1 = this.x + "-" + this.y; String compare2 = other.x + "-" + other.y; return compare1.compareTo( compare2 ); } public String toString() { return this.x + "-" + this.y; } } As of now i cant send it as an object with outputstream..I´ve tried just to implement Serializable but it doesnt do the trick!

    Read the article

  • Searching in a TreeMap (Java)

    - by Kronen
    I need to do a search in a map of maps and return the keys this element belong. I think this implementation is very slow, can you help me to optimize it?. I need to use TreeSet and I can't use contains because they use compareTo, and equals/compareTo pair are implemented in an incompatible way and I can't change that. (sorry my bad english) Map m = new TreeSet(); public String getKeys(Element element) { for(Entry e : m.entrySet()) { mapSubKey = e.getValue(); for(Entry e2 : mapSubKey.entrySet()) { setElements = e2.getValue(); for(Element elem : setElements) if(elem.equals(element)) return "Key: " + e.getKey() + " SubKey: " + e2.getKey(); } } }

    Read the article

  • Lambda expression will not compile

    - by John Soer
    I am very confused. I have this lamba expression: tvPatientPrecriptionsEntities.Sort((p1, p2) => p1.MedicationStartDate .Value .CompareTo(p2.MedicationStartDate.Value)); Visual Studio will not compile it and complains about syntax. I converted the lamba expression to an anonymous delegate as so: tvPatientPrecriptionsEntities.Sort( delegate(PatientPrecriptionsEntity p1, PatientPrecriptionsEntity p2) { return p1.MedicationStartDate .Value .CompareTo(p2.MedicationStartDate.Value); }); and it works fine. The project uses .NET 3.5 and I have a reference to System.Linq.

    Read the article

  • memory leak error when using an iterator

    - by Adnane Jaafari
    please i'm having this error if any one can explain it : while using an iterator in my methode public void createDemandeP() { if (demandep.getDateDebut().after(demandep.getDateFin())) { FacesContext .getCurrentInstance() .addMessage( null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Attention aux dates", "la date de debut doit être avant la date de fin!")); } else if (demandep.getDateDebut().before(demandep.getDateFin())) { List<DemandeP> list = new ArrayList<DemandeP>(); list.addAll(chaletService.getChaletBylibelle(chaletChoisi).get(0) .getListDemandesP()); Iterator<DemandeP> it = list.iterator(); DemandeP d = it.next(); while (it.hasNext()) { if ((d.getDateDebut().compareTo(demandep.getDateDebut()) == 0) || (d.getDateFin().compareTo(demandep.getDateDebut()) == 0) || (d.getDateFin().compareTo(demandep.getDateFin()) == 0) || (d.getDateDebut().compareTo(demandep.getDateDebut()) == 0) || (d.getDateDebut().before(demandep.getDateDebut()) && d .getDateFin().after(demandep.getDateFin())) || (d.getDateDebut().before(demandep.getDateFin()) && d .getDateDebut().after(demandep.getDateDebut())) || (d.getDateFin().after(demandep.getDateDebut()) && d .getDateFin().before(demandep.getDateFin()))) { FacesContext.getCurrentInstance().getMessageList().clear(); FacesContext .getCurrentInstance() .addMessage( null, new FacesMessage( FacesMessage.SEVERITY_FATAL, "Periode Ou chalet indisponicle ", "Veillez choisir une autre marge de date !")); } } } else { demandep.setEtat("En traitement"); DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); Date date = new Date(); try { demandep.setDateDemande(dateFormat.parse(dateFormat .format(date))); } catch (ParseException e) { System.out.println("errooor date"); e.printStackTrace(); } nameUser = auth.getName(); // System.out.println(nameUser); adherent = utilisateurService.findAdherentByNom(nameUser).get(0); demandep.setUtilisateur(adherent); // System.out.println(chaletService.getChaletBylibelle(chaletChoisi).get(0).getLibelle()); demandep.setChalet(chaletService.getChaletBylibelle(chaletChoisi) .get(0)); demandep.setNouvelleDemande(true); demandePService.ajouterDemandeP(demandep); } } oct. 23, 2013 7:19:30 PM org.apache.catalina.core.StandardContext reload INFO: Le rechargement du contexte [/ONICLFINAL] a démarré oct. 23, 2013 7:19:30 PM org.apache.catalina.core.StandardWrapper unload INFO: Waiting for 1 instance(s) to be deallocated oct. 23, 2013 7:19:31 PM org.apache.catalina.core.StandardWrapper unload INFO: Waiting for 1 instance(s) to be deallocated oct. 23, 2013 7:19:32 PM org.apache.catalina.core.StandardWrapper unload INFO: Waiting for 1 instance(s) to be deallocated oct. 23, 2013 7:19:32 PM org.apache.catalina.core.ApplicationContext log INFO: Closing Spring root WebApplicationContext oct. 23, 2013 7:19:32 PM org.apache.catalina.loader.WebappClassLoader clearReferencesJdbc SEVERE: The web application [/ONICLFINAL] registered the JDBC driver [com.mysql.jdbc.Driver] b but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered. oct. 23, 2013 7:19:32 PM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads SEVERE: The web application [/ONICLFINAL] appears to have started a thread named [MySQL Statement Cancellation Timer] but has failed to stop it. This is very likely to create a memory leak. oct. 23, 2013 7:19:32 PM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads SE VERE: The web application [/ONICLFINAL] is still processing a request that has yet to finish. This is very likely to create a memory leak. You can control the time allowed for requests to finish by using the unloadDelay attribute of the standard Context implementation. oct. 23, 2013 7:19:32 PM org.apache.catalina.loader.WebappClassLoader clearThreadLocalMap SEVERE: The web application [/ONICLFINAL] created a ThreadLocal with key of type [org.springframework.core.NamedThreadLocal] (value [Hibernate Sessions registered for deferred close]) and a value of type [java.util.HashMap] (value [{org.hibernate.impl.SessionFactoryImpl@f6e256=[SessionImpl(PersistenceContext[entityKeys=[EntityKey[bo.DemandeP#1], EntityKey[bo.Utilisateur#3], EntityKey[bo.Chalet#1], EntityKey[bo.Role#2], EntityKey[bo.DemandeP#2]],collectionKeys=[CollectionKey[bo.Role.ListeUsers#2], CollectionKey[bo.Chalet.listPeriodes#1], CollectionKey[bo.Utilisateur.demandes#3], CollectionKey[bo.Utilisateur.demandesP#3], CollectionKey[bo.Chalet.listDemandesP#1]]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]])]}]) but failed to remove it when the web application was stopped. This is very likely to create a memory leak. oct. 23, 2013 7:19:32 PM org.apache.catalina.loader.WebappClassLoader clearThreadLocalMap SEVERE: The web application [/ONICLFINAL] created a ThreadLocal with key of type [org.springframework.core.NamedThreadLocal] (value [Request attributes]) and a value of type [org.springframework.web.context.request.ServletRequestAttributes] (value [org.apache.catalina.connector.RequestFacade@17f3488]) but failed to remove it when the web application was stopped. This is very likely to create a memory leak. oct. 23, 2013 7:19:32 PM org.apache.catalina.loader.WebappClassLoader clearThreadLocalMap SEVERE: The web application [/ONICLFINAL] created a ThreadLocal with key of type [java.lang.ThreadLocal] (value [java.lang.ThreadLocal@51f78b]) and a value of type [org.springframework.security.core.context.SecurityContextImpl] (value [org.springframework.security.core.context.SecurityContextImpl@8e463c8b: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@8e463c8b: Principal: org.springframework.security.core.userdetails.User@311aa119: Username: maatouf; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADHER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@ffff4c9c: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 14CD5D4E8E0E3AEB0367AB7115038FED; Granted Authorities: ROLE_ADHER]) but failed to remove it when the web application was stopped. This is very likely to create a memory leak. oct. 23, 2013 7:19:32 PM org.apache.catalina.loader.WebappClassLoader clearThreadLocalMap SEVERE: The web application [/ONICLFINAL] created a ThreadLocal with key of type [java.lang.ThreadLocal] (value [java.lang.ThreadLocal@152e9b7]) and a value of type [net.sf.cglib.proxy.Callback[]] (value [[Lnet.sf.cglib.proxy.Callback;@6e1f4c]) but failed to remove it when the web application was stopped. This is very likely to create a memory leak. oct. 23, 2013 7:19:32 PM org.apache.catalina.loader.WebappClassLoader clearThreadLocalMap SEVERE: The web application [/ONICLFINAL] created a ThreadLocal with key of type [javax.faces.context.FacesContext$1] (value [javax.faces.context.FacesContext$1@9ecc6d]) and a value of type [com.sun.faces.context.FacesContextImpl] (value [com.sun.faces.context.FacesContextImpl@1c8bbed]) but failed to remove it when the web application was stopped. This is very likely to create a memory leak. oct. 23, 2013 7:19:32 PM org.apache.catalina.loader.WebappClassLoader clearThreadLocalMap SEVERE: The web application [/ONICLFINAL] created a ThreadLocal with key of type [java.lang.ThreadLocal] (value [java.lang.ThreadLocal@1a9e75f]) and a value of type [com.sun.faces.context.FacesContextImpl] (value [com.sun.faces.context.FacesContextImpl@1c8bbed]) but failed to remove it when the web application was stopped. This is very likely to create a memory leak. oct. 23, 2013 7:19:32 PM org.apache.catalina.loader.WebappClassLoader clearThreadLocalMap SEVERE: The web application [/ONICLFINAL] created a ThreadLocal with key of type [org.springframework.core.NamedThreadLocal] (value [Locale context]) and a value of type [org.springframework.context.i18n.SimpleLocaleContext] (value [fr_FR]) but failed to remove it when the web application was stopped. This is very likely to create a memory leak. oct. 23, 2013 7:19:32 PM org.apache.catalina.loader.WebappClassLoader clearThreadLocalMap SEVERE: The web application [/ONICLFINAL] created a ThreadLocal with key of type [com.sun.faces.application.ApplicationAssociate$1] (value [com.sun.faces.application.ApplicationAssociate$1@195266b]) and a value of type [com.sun.faces.application.ApplicationAssociate] (value [com.sun.faces.application.ApplicationAssociate@10d595c]) but failed to remove it when the web application was stopped. This is very likely to create a memory leak. oct. 23, 2013 7:19:33 PM org.apache.catalina.loader.WebappClassLoader validateJarFile INFO: validateJarFile(D:\newWorkSpace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\ONICLF INAL\WEB-INF\lib\servlet-api-2.5.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class oct. 23, 2013 7:19:33 PM org.apache.catalina.core.ApplicationContext log

    Read the article

  • Unable to add separator in list view

    - by Suru
    This is my code @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.email_list_main); emailResults = new ArrayList<GetEmailFromDatabase>(); //int[] colors = {0,0xFFFF0000,0}; //getListView().setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors)); //getListView().setDividerHeight(2); emailListFeedAdapter = new EmailListFeedAdapter(this, R.layout.email_listview_row, emailResults); setListAdapter(this.emailListFeedAdapter); getResults(); if(emailResults != null && emailResults.size() > -1){ emailListFeedAdapter.notifyDataSetChanged(); for(int i=0;i< emailResults.size();i++){ try { Here I getting email Sent date emailListFeedAdapter.add( emailResults.get(i)); datetime_text1 = emailResults.get(i).getDate(); formatter1 = new SimpleDateFormat(); formatter1 = DateFormat.getDateInstance((DateFormat.MEDIUM)); Calendar currentDate1 = Calendar.getInstance(); Item_Date1 = formatter1.parse(datetime_text1); current_Date1 = formatter1.format(currentDate1.getTime()); current_System_Date1 = formatter1.parse(current_Date1); currentDate1.add(Calendar.DATE, -1); yesterdaydate = formatter1.format(currentDate1.getTime()); yeaterday_Date = formatter1.parse(yesterdaydate); currentDate1.add(Calendar.DATE, -2); threeDaysback = formatter1.format(currentDate1.getTime()); Three_Days_Back = formatter1.parse(threeDaysback); Here I am comparing current date with list view item date, and here is my problem, dates are matching but it is not entering in if condition I tried in so many ways but nothing worked the code for separator is bellow. if(Item_Date.compareTo(current_System_Date)==0){ if(index1){ emailListFeedAdapter.addSeparatorItem("SEPARATOR"); //i--; index1=false; } } else if(yeaterday_Date.compareTo(Item_Date1)==0){ if(index2){ emailListFeedAdapter.addSeparatorItem("SEPARATOR"); //i--; index2 = false; } } else if(Item_Date1.compareTo(Three_Days_Back)==0){ if(index3){ emailListFeedAdapter.addSeparatorItem("SEPARATOR"); //i--; index3 = false; } } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } In EmailListFeedAdapter private TreeSet<Integer> mSeparatorsSet = new TreeSet<Integer>(); public void addSeparatorItem(final String item) { //itemss.add(emailResults.get(0)); // save separator position mSeparatorsSet.add(itemss.size() - 1); notifyDataSetChanged(); } @Override public int getItemViewType(int position) { return mSeparatorsSet.contains(position) ? TYPE_SEPARATOR : TYPE_ITEM; } holder = new ViewHolder(); switch (type) { case TYPE_ITEM: emailView= inflater.inflate(R.layout.email_listview_row, null); break; case TYPE_SEPARATOR: emailView= inflater.inflate(R.layout.item2, null); holder.textView = (TextView)emailView.findViewById(R.id.textSeparator); emailView.setTag(holder); holder.textView.setText("SEPARATOR"); break; } Here is ViewHolder class public static class ViewHolder { public TextView textView; } if anybody knows then please tell me where I am doing wrong. Thanx

    Read the article

  • Using Comparable to compare objects and sorting them in a TreeMap

    - by arjacsoh
    II cannot understand how should the natural ordering of class be "consistent with equals" when implementing the Comparable interface. I deteted a flaw in my program and therefore I deteced that in the documentantion of the interface Comparable. My problem is that although two Objects are considered as distinct on the base of equals method, the TreeMap structure treats them as equal and consequently does not accept the second insert. The sample code is: public class Car implements Comparable<Car> { int weight; String name; public Car(int w, String n) { weight=w; name=n; } public boolean equals(Object o){ if(o instanceof Car){ Car d = (Car)o; return ((d.name.equals(name)) && (d.weight==weight)); } return false; } public int hashCode(){ return weight/2 + 17; } public String toString(){ return "I am " +name+ " !!!"; } public int compareTo(Car d){ if(this.weight>d.weight) return 1; else if(this.weight<d.weight) return -1; else return 0; } /*public int compareTo(Car d){ return this.name.compareTo(d.name); }*/ } public static void main(String[] args) { Car d1 = new Car(100, "a"); Car d2 = new Car(110, "b"); Car d3 = new Car(110, "c"); Car d4 = new Car(100, "a"); Map<Car, Integer> m = new HashMap<Car, Integer>(); m.put(d1, 1); m.put(d2, 2); m.put(d3, 3); m.put(d4, 16); for(Map.Entry<Car, Integer> me : m.entrySet()) System.out.println(me.getKey().toString() + " " +me.getValue()); TreeMap<Car, Integer> tm = new TreeMap<Car, Integer>(m); System.out.println("After Sorting: "); for(Map.Entry<Car, Integer> me : tm.entrySet()) System.out.println(me.getKey().toString() + " " +me.getValue()); } The output is : I am a !!! 16 I am c !!! 3 I am b !!! 2 After Sorting: I am a !!! 16 I am c !!! 2 That is, that the object c has replaced (somewhat) object b. If I comment the original equals method and uncomment the second equals method, which compares the objects according name, the output is the expected: I am a !!! 16 I am c !!! 3 I am b !!! 2 After Sorting: I am a !!! 16 I am b !!! 2 I am c !!! 3 Why does it come around in this way and what should I alter in order to insert and sort different objects with some attributes of equal value in a TreeMap?

    Read the article

  • IComparer using Lambda Expression

    - by josephj1989
    class p { public string Name { get; set; } public int Age { get; set; } }; static List<p> ll = new List<p> { new p{Name="Jabc",Age=53},new p{Name="Mdef",Age=20}, new p{Name="Exab",Age=45},new p{Name="G123",Age=19} }; protected static void SortList() { IComparer<p> mycomp = (x, y) => x.Name.CompareTo(y.Name); <==(Line 1) ll.Sort((x, y) => x.Name.CompareTo(y.Name));<==(Line 2) } Here the List.sort expects an IComparer<p> as a parameter. And it works with the lambda as shown in Line 2. But when I try to do as in Line 1, I get an error: Cannot convert lambda expression to type System.Collections.Generic.IComparer' because it is not a delegate type I investigated this for quite some time but I still don't understand it. Maybe my understanding of IComparer is not quite good.

    Read the article

  • problem while removing an element from the TreeSet

    - by harshit
    I am doing the following class RuleObject implements Comparable{ @Override public String toString() { return "RuleObject [colIndex=" + colIndex + ", probability=" + probability + ", rowIndex=" + rowIndex + ", rule=" + rule + "]"; } String rule; double probability; int rowIndex; int colIndex; public RuleObject(String rule, double probability) { this.rule = rule; this.probability = probability; } @Override public int compareTo(Object o) { RuleObject ruleObj = (RuleObject)o; System.out.println(ruleObj); System.out.println("---------------"); System.out.println(this); if(ruleObj.probability > probability) return 1; else if(ruleObj.probability < probability) return -1; else{ if(ruleObj.colIndex == this.colIndex && ruleObj.rowIndex == this.rowIndex && ruleObj.probability == this.probability && ruleObj.rule.equals(this.rule)) return 0; } return 1; } } And I have a TreeSet containing elements of RuleObject. I am trying to do the following : System.out.println(sortedHeap.size()); RuleObject ruleObj = sortedHeap.first(); sortedHeap.remove(ruleObj); System.out.println(sortedHeap.size()); I can see that the size of set remains same. I am not able to understand why is it not being deleted. Also while deleting I could see compareTo method is called. But it is called for only 3 object whereas in set there are 8 objects. Thanks

    Read the article

  • Java, LinkedList of Strings. Insert in alphabetical order

    - by user69514
    I have a simple linked list. The node contains a string (value) and an int (count). In the linkedlist when I insert I need to insert the new Node in alphabetical order. If there is a node with the same value in the list, then I simply increment the count of the node. I think I got my method really screwed up. public void addToList(Node node){ //check if list is empty, if so insert at head if(count == 0 ){ head = node; head.setNext(null); count++; } else{ Node temp = head; for(int i=0; i<count; i++){ //if value is greater, insert after if(node.getItem().getValue().compareTo(temp.getItem().getValue()) > 0){ node.setNext(temp.getNext()); temp.setNext(node); } //if value is equal just increment the counter else if(node.getItem().getValue().compareTo(temp.getItem().getValue()) == 0){ temp.getItem().setCount(temp.getItem().getCount() + 1); } //else insert before else{ node.setNext(temp); } } } }

    Read the article

  • C# .NET: Descending comparison of a SortedDictionary?

    - by Rosarch
    I'm want a IDictionary<float, foo> that returns the larges values of the key first. private IDictionary<float, foo> layers = new SortedDictionary<float, foo>(new DescendingComparer<float>()); class DescendingComparer<T> : IComparer<T> where T : IComparable<T> { public int Compare(T x, T y) { return -y.CompareTo(x); } } However, this returns values in order of the smallest first. I feel like I'm making a stupid mistake here. Just to see what would happen, I removed the - sign from the comparator: public int Compare(T x, T y) { return y.CompareTo(x); } But I got the same result. This reinforces my intuition that I'm making a stupid error. This is the code that accesses the dictionary: foreach (KeyValuePair<float, foo> kv in sortedLayers) { // ... } UPDATE: This works, but is too slow to call as frequently as I need to call this method: IOrderedEnumerable<KeyValuePair<float, foo>> sortedLayers = layers.OrderByDescending(kv => kv.Key); foreach (KeyValuePair<float, ICollection<IGameObjectController>> kv in sortedLayers) { // ... } UPDATE: I put a break point in the comparator that never gets hit as I add and remove kv pairs from the dictionary. What could this mean?

    Read the article

  • Java - abstract class, equals(), and two subclasses

    - by msr
    Hello, I have an abstract class named Xpto and two subclasses that extend it named Person and Car. I have also a class named Test with main() and a method foo() that verifies if two persons or cars (or any object of a class that extends Xpto) are equals. Thus, I redefined equals() in both Person and Car classes. Two persons are equal when they have the same name and two cars are equal when they have the same registration. However, when I call foo() in the Test class I always get "false". I understand why: the equals() is not redefined in Xpto abstract class. So... how can I compare two persons or cars (or any object of a class that extends Xpto) in that foo() method? In summary, this is the code I have: public abstract class Xpto { } public class Person extends Xpto{ protected String name; public Person(String name){ this.name = name; } public boolean equals(Person p){ System.out.println("Person equals()?"); return this.name.compareTo(p.name) == 0 ? true : false; } } public class Car extends Xpto{ protected String registration; public Car(String registration){ this.registration = registration; } public boolean equals(Car car){ System.out.println("Car equals()?"); return this.registration.compareTo(car.registration) == 0 ? true : false; } } public class Teste { public static void foo(Xpto xpto1, Xpto xpto2){ if(xpto1.equals(xpto2)) System.out.println("xpto1.equals(xpto2) -> true"); else System.out.println("xpto1.equals(xpto2) -> false"); } public static void main(String argv[]){ Car c1 = new Car("ABC"); Car c2 = new Car("DEF"); Person p1 = new Person("Manel"); Person p2 = new Person("Manel"); foo(p1,p2); } }

    Read the article

  • Need help coming up with a better HtmlHelper Extension method.

    - by zSysop
    Hi all, I've inherited the following code and i was wondering if i could pick at your brains to see if there's a nicer way to do duplicate this. Heres the html for most of our partial input views <% if (Html.IsInputReadOnly()) { %> <td> Id </td> <td> <%= Html.TextBox( "Id" , (Model == null ? null : Model.Id) , new { @readonly = "readonly", @disabled="disabled" } )%> <% } elseif (Html.IsInputDisplayable() == false) { %> <td></td> <td></td> <% } else { %> <td>Id</td> <td><%= Html.TextBox("Id")%> <%= Html.ValidationMessage("Id", "*")%> </td> <%} %> Here are my entension methods public static bool IsInputReadOnly(this HtmlHelper helper) { string actionName = ActionName(helper); // The Textbox should be read only on all pages except for the lookup page if (actionName.ToUpper().CompareTo("EDIT") == 0) return true; return false; } public static bool IsInputDisplayable(this HtmlHelper helper) { string actionName = ActionName(helper); // The Textbox should be read only on all pages except for the lookup page if (actionName.ToUpper().CompareTo("CREATE") == 0) return true; return false; } Thanks in advance

    Read the article

  • Java: How to workaround the lack of Equatable interface?

    - by java.is.for.desktop
    Hello, everyone! As far as I know, things such as SortedMap or SortedSet, use compareTo (rather than equals) on Comparable<?> types for checking equality (contains, containsKey). But what if certain types are equatable by concept, but not comparable? I have to declare a Comparator<?> and override the method int compareTo(T o1, To2). OK, I can return 0 for instances which are considered equal. But, for unqeual instances, what do I return when an order is not evident? Is the approach of using SortedMap or SortedSet on equatable but (by concept) not comparable types good anyway? Thank you! EDIT: I don't want to store things sorted, but would I use "usual" Map and Set, I couldn't "override" the equality-behavior. EDIT 2: Why I can't just override equals(...): I need to alter the equality-behavior of a foreign class. Can't edit it. EDIT 3: Just think of .NET: They have IEquatable interface which cat alter the equality-behavior without touching the comparable behavior.

    Read the article

  • Generic InBetween Function.

    - by Luiscencio
    I am tired of writing x > min && x < max so i wawnt to write a simple function but I am not sure if I am doing it right... actually I am not cuz I get an error: bool inBetween<T>(T x, T min, T max) where T:IComparable { return (x > min && x < max); } errors: Operator '>' cannot be applied to operands of type 'T' and 'T' Operator '<' cannot be applied to operands of type 'T' and 'T' may I have a bad understanding of the where part in the function declaring note: for those who are going to tell me that I will be writing more code than before... think on readability =) any help will be appreciated EDIT deleted cuz it was resolved =) ANOTHER EDIT so after some headache I came out with this (ummm) thing following @Jay Idea of extreme readability: public static class test { public static comparision Between<T>(this T a,T b) where T : IComparable { var ttt = new comparision(); ttt.init(a); ttt.result = a.CompareTo(b) > 0; return ttt; } public static bool And<T>(this comparision state, T c) where T : IComparable { return state.a.CompareTo(c) < 0 && state.result; } public class comparision { public IComparable a; public bool result; public void init<T>(T ia) where T : IComparable { a = ia; } } } now you can compare anything with extreme readability =) what do you think.. I am no performance guru so any tweaks are welcome

    Read the article

  • C# functional quicksort is failing

    - by Rubys
    I'm trying to implement quicksort in a functional style using C# using linq, and this code randomly works/doesn't work, and I can't figure out why. Important to mention: When I call this on an array or list, it works fine. But on an unknown-what-it-really-is IEnumerable, it goes insane (loses values or crashes, usually. sometimes works.) The code: public static IEnumerable<T> Quicksort<T>(this IEnumerable<T> source) where T : IComparable<T> { if (!source.Any()) yield break; var pivot = source.First(); var sortedQuery = source.Skip(1).Where(a => a.CompareTo(source.First()) <= 0).Quicksort() .Concat(new[] { pivot }) .Concat(source.Skip(1).Where(a => a.CompareTo(source.First()) > 0).Quicksort()); foreach (T key in sortedQuery) yield return key; } Can you find any faults here that would cause this to fail?

    Read the article

  • How to create custom query for CollectionOfElements

    - by Shervin
    Hi. I have problems creating a custom query. This is what entities: @Entity public class ApplicationProcess { @CollectionOfElements private Set<Template> defaultTemplates; //more fields } And Template.java @Embeddable @EqualsAndHashCode(exclude={"file", "selected", "used"}) public class Template implements Comparable<Template> { @Setter private ApplicationProcess applicationProcess; @Setter private Boolean used = Boolean.valueOf(false); public Template() { } @Parent public ApplicationProcess getApplicationProcess() { return applicationProcess; } @Column(nullable = false) @NotNull public String getName() { return name; } @Column(nullable = true) public Boolean isUsed() { return used; } public int compareTo(Template o) { return getName().compareTo(o.getName()); } } I want to create a update statement. I have tried these two: int v = entityManager.createQuery("update ApplicationProcess_defaultTemplates t set t.used = true " + "WHERE t.applicationProcess.id=:apId").setParameter("apId", ap.getId()) .executeUpdate(); ApplicationProcess_defaultTemplates is not mapped [update ApplicationProcess_defaultTemplates t set t.used = true WHERE t.applicationProcess.id=:apId] And I have tried int v = entityManager.createQuery("update Template t set t.used = true " + "WHERE t.applicationProcess.id=:apId").setParameter("apId", ap.getId()) .executeUpdate(); With the same error: Template is not mapped [update Template t set t.used = true WHERE t.applicationProcess.id=:apId] Any ideas? UPDATE I fixed it by creating native query int v = entityManager.createNativeQuery("update ApplicationProcess_defaultTemplates t set t.used=true where t.ApplicationProcess_id=:apId").setParameter("apId", ap.getId()).executeUpdate();

    Read the article

  • Modular Inverse and BigInteger division

    - by dano82
    I've been working on the problem of calculating the modular inverse of an large integer i.e. a^-1 mod n. and have been using BigInteger's built in function modInverse to check my work. I've coded the algorithm as shown in The Handbook of Applied Cryptography by Menezes, et al. Unfortunately for me, I do not get the correct outcome for all integers. My thinking is that the line q = a.divide(b) is my problem as the divide function is not well documented (IMO)(my code suffers similarly). Does BigInteger.divide(val) round or truncate? My assumption is truncation since the docs say that it mimics int's behavior. Any other insights are appreciated. This is the code that I have been working with: private static BigInteger modInverse(BigInteger a, BigInteger b) throws ArithmeticException { //make sure a >= b if (a.compareTo(b) < 0) { BigInteger temp = a; a = b; b = temp; } //trivial case: b = 0 => a^-1 = 1 if (b.equals(BigInteger.ZERO)) { return BigInteger.ONE; } //all other cases BigInteger x2 = BigInteger.ONE; BigInteger x1 = BigInteger.ZERO; BigInteger y2 = BigInteger.ZERO; BigInteger y1 = BigInteger.ONE; BigInteger x, y, q, r; while (b.compareTo(BigInteger.ZERO) == 1) { q = a.divide(b); r = a.subtract(q.multiply(b)); x = x2.subtract(q.multiply(x1)); y = y2.subtract(q.multiply(y1)); a = b; b = r; x2 = x1; x1 = x; y2 = y1; y1 = y; } if (!a.equals(BigInteger.ONE)) throw new ArithmeticException("a and n are not coprime"); return x2; }

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8  | Next Page >