Search Results

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

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

  • Is this Leftist Tree piece of code from Wikipedia correct?

    - by they changed my name
    Link public Node merge(Node x, Node y) { if(x == null) return y; if(y == null) return x; // if this was a max height biased leftist tree, then the // next line would be: if(x.element < y.element) if(x.element.compareTo(y.element) > 0) { // x.element > y.element Node temp = x; x = y; y = temp; } x.rightChild = merge(x.rightChild, y); if(x.leftChild == null) { // left child doesn't exist, so move right child to the left side x.leftChild = x.rightChild; x.rightChild = null; x.s = 1; } else { // left child does exist, so compare s-values if(x.leftChild.s < x.rightChild.s) { Node temp = x.leftChild; x.leftChild = x.rightChild; x.rightChild = temp; } // since we know the right child has the lower s-value, we can just // add one to its s-value x.s = x.rightChild.s + 1; } return x; } What makes me ask this question is: if(x.element.compareTo(y.element) > 0) { // x.element > y.element Node temp = x; x = y; y = temp; } Isn't that just not gonna work, since the references are only switched inside the method?

    Read the article

  • How is this function being made use of?

    - by Kay
    Hello all, I am just studying a few classes given to me by my lecturer and I can't understand how the function heapRebuild is being made used of! It doesn't change any global variables and it doesn't print out anything ad it doesn't return anything - so should this even work? It shouldn't, should it? If you were told to make use of heapRebuild to make a new function removeMac would you edit heapRebuild? public class MaxHeap<T extends Comparable<T>> implements Heap<T>{ private T[] heap; private int lastIndex; public T removeMax(){ T rootItem = heap[0]; heap[0] = heap[lastIndex-1]; lastIndex--; heapRebuild(heap, 0, lastIndex); return rootItem; } protected void heapRebuild(T[ ] items, int root, int size){ int child = 2*root+1; if( child < size){ int rightChild = child+1; if ((rightChild < size) && (items[rightChild].compareTo(items[child]) > 0)){ child = rightChild; } if (items[root].compareTo(items[child]) < 0){ T temp = items[root]; items[root] = items[child]; items[child] = temp; heapRebuild(items, child, size);} } } }

    Read the article

  • How do implement a breadth first traversal?

    - by not looking for answer
    //This is what I have. I thought pre-order was the same and mixed it up with depth first! import java.util.LinkedList; import java.util.Queue; public class Exercise25_1 { public static void main(String[] args) { BinaryTree tree = new BinaryTree(new Integer[] {10, 5, 15, 12, 4, 8 }); System.out.print("\nInorder: "); tree.inorder(); System.out.print("\nPreorder: "); tree.preorder(); System.out.print("\nPostorder: "); tree.postorder(); //call the breadth method to test it System.out.print("\nBreadthFirst:"); tree.breadth(); } } class BinaryTree { private TreeNode root; /** Create a default binary tree */ public BinaryTree() { } /** Create a binary tree from an array of objects */ public BinaryTree(Object[] objects) { for (int i = 0; i < objects.length; i++) { insert(objects[i]); } } /** Search element o in this binary tree */ public boolean search(Object o) { return search(o, root); } public boolean search(Object o, TreeNode root) { if (root == null) { return false; } if (root.element.equals(o)) { return true; } else { return search(o, root.left) || search(o, root.right); } } /** Return the number of nodes in this binary tree */ public int size() { return size(root); } public int size(TreeNode root) { if (root == null) { return 0; } else { return 1 + size(root.left) + size(root.right); } } /** Return the depth of this binary tree. Depth is the * number of the nodes in the longest path of the tree */ public int depth() { return depth(root); } public int depth(TreeNode root) { if (root == null) { return 0; } else { return 1 + Math.max(depth(root.left), depth(root.right)); } } /** Insert element o into the binary tree * Return true if the element is inserted successfully */ public boolean insert(Object o) { if (root == null) { root = new TreeNode(o); // Create a new root } else { // Locate the parent node TreeNode parent = null; TreeNode current = root; while (current != null) { if (((Comparable)o).compareTo(current.element) < 0) { parent = current; current = current.left; } else if (((Comparable)o).compareTo(current.element) > 0) { parent = current; current = current.right; } else { return false; // Duplicate node not inserted } } // Create the new node and attach it to the parent node if (((Comparable)o).compareTo(parent.element) < 0) { parent.left = new TreeNode(o); } else { parent.right = new TreeNode(o); } } return true; // Element inserted } public void breadth() { breadth(root); } // Implement this method to produce a breadth first // search traversal public void breadth(TreeNode root){ if (root == null) return; System.out.print(root.element + " "); breadth(root.left); breadth(root.right); } /** Inorder traversal */ public void inorder() { inorder(root); } /** Inorder traversal from a subtree */ private void inorder(TreeNode root) { if (root == null) { return; } inorder(root.left); System.out.print(root.element + " "); inorder(root.right); } /** Postorder traversal */ public void postorder() { postorder(root); } /** Postorder traversal from a subtree */ private void postorder(TreeNode root) { if (root == null) { return; } postorder(root.left); postorder(root.right); System.out.print(root.element + " "); } /** Preorder traversal */ public void preorder() { preorder(root); } /** Preorder traversal from a subtree */ private void preorder(TreeNode root) { if (root == null) { return; } System.out.print(root.element + " "); preorder(root.left); preorder(root.right); } /** Inner class tree node */ private class TreeNode { Object element; TreeNode left; TreeNode right; public TreeNode(Object o) { element = o; } } }

    Read the article

  • How can I resolve Hibernate 3's ConstraintViolationException when updating a Persistent Entity's Col

    - by Tim Visher
    I'm trying to discover why two nearly identical class sets are behaving different from Hibernate 3's perspective. I'm fairly new to Hibernate in general and I'm hoping I'm missing something fairly obvious about the mappings or timing issues or something along those lines but I spent the whole day yesterday staring at the two sets and any differences that would lead to one being able to be persisted and the other not completely escaped me. I appologize in advance for the length of this question but it all hinges around some pretty specific implementation details. I have the following class mapped with Annotations and managed by Hibernate 3.? (if the specific specific version turns out to be pertinent, I'll figure out what it is). Java version is 1.6. ... @Embeddable public class JobStateChange implements Comparable<JobStateChange> { @Temporal(TemporalType.TIMESTAMP) @Column(nullable = false) private Date date; @Enumerated(EnumType.STRING) @Column(nullable = false, length = JobState.FIELD_LENGTH) private JobState state; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "acting_user_id", nullable = false) private User actingUser; public JobStateChange() { } @Override public int compareTo(final JobStateChange o) { return this.date.compareTo(o.date); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } else if (!(obj instanceof JobStateChange)) { return false; } JobStateChange candidate = (JobStateChange) obj; return this.state == candidate.state && this.actingUser.equals(candidate.getUser()) && this.date.equals(candidate.getDate()); } @Override public int hashCode() { return this.state.hashCode() + this.actingUser.hashCode() + this.date.hashCode(); } } It is mapped as a Hibernate CollectionOfElements in the class Job as follows: ... @Entity @Table( name = "job", uniqueConstraints = { @UniqueConstraint( columnNames = { "agency", //Job Name "payment_type", //Job Name "payment_file", //Job Name "date_of_payment", "payment_control_number", "truck_number" }) }) public class Job implements Serializable { private static final long serialVersionUID = -1131729422634638834L; ... @org.hibernate.annotations.CollectionOfElements @JoinTable(name = "job_state", joinColumns = @JoinColumn(name = "job_id")) @Sort(type = SortType.NATURAL) private final SortedSet<JobStateChange> stateChanges = new TreeSet<JobStateChange>(); ... public void advanceState( final User actor, final Date date) { JobState nextState; LOGGER.debug("Current state of {} is {}.", this, this.getCurrentState()); if (null == this.currentState) { nextState = JobState.BEGINNING; } else { if (!this.isAdvanceable()) { throw new IllegalAdvancementException(this.currentState.illegalAdvancementStateMessage); } if (this.currentState.isDivergent()) { nextState = this.currentState.getNextState(this); } else { nextState = this.currentState.getNextState(); } } JobStateChange stateChange = new JobStateChange(nextState, actor, date); this.setCurrentState(stateChange.getState()); this.stateChanges.add(stateChange); LOGGER.debug("Advanced {} to {}", this, this.getCurrentState()); } private void setCurrentState(final JobState jobState) { this.currentState = jobState; } boolean isAdvanceable() { return this.getCurrentState().isAdvanceable(this); } ... @Override public boolean equals(final Object obj) { if (obj == this) { return true; } else if (!(obj instanceof Job)) { return false; } Job otherJob = (Job) obj; return this.getName().equals(otherJob.getName()) && this.getDateOfPayment().equals(otherJob.getDateOfPayment()) && this.getPaymentControlNumber().equals(otherJob.getPaymentControlNumber()) && this.getTruckNumber().equals(otherJob.getTruckNumber()); } @Override public int hashCode() { return this.getName().hashCode() + this.getDateOfPayment().hashCode() + this.getPaymentControlNumber().hashCode() + this.getTruckNumber().hashCode(); } ... } The purpose of JobStateChange is to record when the Job moves through a series of State Changes that are outline in JobState as enums which know about advancement and decrement rules. The interface used to advance Jobs through a series of states is to call Job.advanceState() with a Date and a User. If the Job is advanceable according to rules coded in the enum, then a new StateChange is added to the SortedSet and everyone's happy. If not, an IllegalAdvancementException is thrown. The DDL this generates is as follows: ... drop table job; drop table job_state; ... create table job ( id bigint generated by default as identity, current_state varchar(25), date_of_payment date not null, beginningCheckNumber varchar(8) not null, item_count integer, agency varchar(10) not null, payment_file varchar(25) not null, payment_type varchar(25) not null, endingCheckNumber varchar(8) not null, payment_control_number varchar(4) not null, truck_number varchar(255) not null, wrapping_system_type varchar(15) not null, printer_id bigint, primary key (id), unique (agency, payment_type, payment_file, date_of_payment, payment_control_number, truck_number) ); create table job_state ( job_id bigint not null, acting_user_id bigint not null, date timestamp not null, state varchar(25) not null, primary key (job_id, acting_user_id, date, state) ); ... alter table job add constraint FK19BBD12FB9D70 foreign key (printer_id) references printer; alter table job_state add constraint FK57C2418FED1F0D21 foreign key (acting_user_id) references app_user; alter table job_state add constraint FK57C2418FABE090B3 foreign key (job_id) references job; ... The database is seeded with the following data prior to running tests ... insert into job (id, agency, payment_type, payment_file, payment_control_number, date_of_payment, beginningCheckNumber, endingCheckNumber, item_count, current_state, printer_id, wrapping_system_type, truck_number) values (-3, 'RRB', 'Monthly', 'Monthly','4501','1998-12-01 08:31:16' , '00000001','00040000', 40000, 'UNASSIGNED', null, 'KERN', '02'); insert into job_state (job_id, acting_user_id, date, state) values (-3, -1, '1998-11-30 08:31:17', 'UNASSIGNED'); ... After the database schema is automatically generated and rebuilt by the Hibernate tool. The following test runs fine up until the call to Session.flush() ... @ContextConfiguration(locations = { "/applicationContext-data.xml", "/applicationContext-service.xml" }) public class JobDaoIntegrationTest extends AbstractTransactionalJUnit4SpringContextTests { @Autowired private JobDao jobDao; @Autowired private SessionFactory sessionFactory; @Autowired private UserService userService; @Autowired private PrinterService printerService; ... @Test public void saveJob_JobAdvancedToAssigned_AllExpectedStateChanges() { //Get an unassigned Job Job job = this.jobDao.getJob(-3L); assertEquals(JobState.UNASSIGNED, job.getCurrentState()); Date advancedToUnassigned = new GregorianCalendar(1998, 10, 30, 8, 31, 17).getTime(); assertEquals(advancedToUnassigned, job.getStateChange(JobState.UNASSIGNED).getDate()); //Satisfy advancement constraints and advance job.setPrinter(this.printerService.getPrinter(-1L)); Date advancedToAssigned = new Date(); job.advanceState( this.userService.getUserByUsername("admin"), advancedToAssigned); assertEquals(JobState.ASSIGNED, job.getCurrentState()); assertEquals(advancedToUnassigned, job.getStateChange(JobState.UNASSIGNED).getDate()); assertEquals(advancedToAssigned, job.getStateChange(JobState.ASSIGNED).getDate()); //Persist to DB this.sessionFactory.getCurrentSession().flush(); ... } ... } The error thrown is SQLCODE=-803, SQLSTATE=23505: could not insert collection rows: [jaci.model.job.Job.stateChanges#-3] org.hibernate.exception.ConstraintViolationException: could not insert collection rows: [jaci.model.job.Job.stateChanges#-3] at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:94) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.persister.collection.AbstractCollectionPersister.insertRows(AbstractCollectionPersister.java:1416) at org.hibernate.action.CollectionUpdateAction.execute(CollectionUpdateAction.java:86) at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:263) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:170) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027) at jaci.dao.JobDaoIntegrationTest.saveJob_JobAdvancedToAssigned_AllExpectedStateChanges(JobDaoIntegrationTest.java:98) at org.springframework.test.context.junit4.SpringTestMethod.invoke(SpringTestMethod.java:160) at org.springframework.test.context.junit4.SpringMethodRoadie.runTestMethod(SpringMethodRoadie.java:233) at org.springframework.test.context.junit4.SpringMethodRoadie$RunBeforesThenTestThenAfters.run(SpringMethodRoadie.java:333) at org.springframework.test.context.junit4.SpringMethodRoadie.runWithRepetitions(SpringMethodRoadie.java:217) at org.springframework.test.context.junit4.SpringMethodRoadie.runTest(SpringMethodRoadie.java:197) at org.springframework.test.context.junit4.SpringMethodRoadie.run(SpringMethodRoadie.java:143) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:160) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:97) Caused by: com.ibm.db2.jcc.b.lm: DB2 SQL Error: SQLCODE=-803, SQLSTATE=23505, SQLERRMC=1;ACI_APP.JOB_STATE, DRIVER=3.50.152 at com.ibm.db2.jcc.b.wc.a(wc.java:575) at com.ibm.db2.jcc.b.wc.a(wc.java:57) at com.ibm.db2.jcc.b.wc.a(wc.java:126) at com.ibm.db2.jcc.b.tk.b(tk.java:1593) at com.ibm.db2.jcc.b.tk.c(tk.java:1576) at com.ibm.db2.jcc.t4.db.k(db.java:353) at com.ibm.db2.jcc.t4.db.a(db.java:59) at com.ibm.db2.jcc.t4.t.a(t.java:50) at com.ibm.db2.jcc.t4.tb.b(tb.java:200) at com.ibm.db2.jcc.b.uk.Gb(uk.java:2355) at com.ibm.db2.jcc.b.uk.e(uk.java:3129) at com.ibm.db2.jcc.b.uk.zb(uk.java:568) at com.ibm.db2.jcc.b.uk.executeUpdate(uk.java:551) at org.hibernate.jdbc.NonBatchingBatcher.addToBatch(NonBatchingBatcher.java:46) at org.hibernate.persister.collection.AbstractCollectionPersister.insertRows(AbstractCollectionPersister.java:1389) Therein lies my problem… A nearly identical Class set (in fact, so identical that I've been chomping at the bit to make it a single class that serves both business entities) runs absolutely fine. It is identical except for name. Instead of Job it's Web. Instead of JobStateChange it's WebStateChange. Instead of JobState it's WebState. Both Job and Web's SortedSet of StateChanges are mapped as a Hibernate CollectionOfElements. Both are @Embeddable. Both are SortType.Natural. Both are backed by an Enumeration with some advancement rules in it. And yet when a nearly identical test is run for Web, no issue is discovered and the data flushes fine. For the sake of brevity I won't include all of the Web classes here, but I will include the test and if anyone wants to see the actual sources, I'll include them (just leave a comment). The data seed: insert into web (id, stock_type, pallet, pallet_id, date_received, first_icn, last_icn, shipment_id, current_state) values (-1, 'PF', '0011', 'A', '2008-12-31 08:30:02', '000000001', '000080000', -1, 'UNSTAGED'); insert into web_state (web_id, date, state, acting_user_id) values (-1, '2008-12-31 08:30:03', 'UNSTAGED', -1); The test: ... @ContextConfiguration(locations = { "/applicationContext-data.xml", "/applicationContext-service.xml" }) public class WebDaoIntegrationTest extends AbstractTransactionalJUnit4SpringContextTests { @Autowired private WebDao webDao; @Autowired private UserService userService; @Autowired private SessionFactory sessionFactory; ... @Test public void saveWeb_WebAdvancedToNewState_AllExpectedStateChanges() { Web web = this.webDao.getWeb(-1L); Date advancedToUnstaged = new GregorianCalendar(2008, 11, 31, 8, 30, 3).getTime(); assertEquals(WebState.UNSTAGED, web.getCurrentState()); assertEquals(advancedToUnstaged, web.getState(WebState.UNSTAGED).getDate()); Date advancedToStaged = new Date(); web.advanceState( this.userService.getUserByUsername("admin"), advancedToStaged); this.sessionFactory.getCurrentSession().flush(); web = this.webDao.getWeb(web.getId()); assertEquals( "Web should have moved to STAGED State.", WebState.STAGED, web.getCurrentState()); assertEquals(advancedToUnstaged, web.getState(WebState.UNSTAGED).getDate()); assertEquals(advancedToStaged, web.getState(WebState.STAGED).getDate()); assertNotNull(web.getState(WebState.UNSTAGED)); assertNotNull(web.getState(WebState.STAGED)); } ... } As you can see, I assert that the Web was reconstituted the way I expect, I advance it, flush it to the DB, and then re-get it and verify that the states are as I expect. Everything works perfectly. Not so with Job. A possibly pertinent detail: the reconstitution code works fine if I cease to map JobStateChange.data as a TIMESTAMP and instead as a DATE, and ensure that all of the StateChanges always occur on different Dates. The problem is that this particular business entity can go through many state changes in a single day and so it needs to be sorted by time stamp rather than by date. If I don't do this then I can't sort the StateChanges correctly. That being said, WebStateChange.date is also mapped as a TIMESTAMP and so I again remain absolutely befuddled as to where this error is arising from. I tried to do a fairly thorough job of giving all of the technical details of the implementation but as this particular question is very implementation specific, if I missed anything just let me know in the comments and I'll include it. Thanks so much for your help! UPDATE: Since it turns out to be important to the solution of my problem, I have to include the pertinent bits of the WebStateChange class as well. ... @Embeddable public class WebStateChange implements Comparable<WebStateChange> { @Temporal(TemporalType.TIMESTAMP) @Column(nullable = false) private Date date; @Enumerated(EnumType.STRING) @Column(nullable = false, length = WebState.FIELD_LENGTH) private WebState state; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "acting_user_id", nullable = false) private User actingUser; ... WebStateChange( final WebState state, final User actingUser, final Date date) { ExceptionUtils.illegalNullArgs(state, actingUser, date); this.state = state; this.actingUser = actingUser; this.date = new Date(date.getTime()); } @Override public int compareTo(final WebStateChange otherStateChange) { return this.date.compareTo(otherStateChange.date); } @Override public boolean equals(final Object candidate) { if (this == candidate) { return true; } else if (!(candidate instanceof WebStateChange)) { return false; } WebStateChange candidateWebState = (WebStateChange) candidate; return this.getState() == candidateWebState.getState() && this.getUser().equals(candidateWebState.getUser()) && this.getDate().equals(candidateWebState.getDate()); } @Override public int hashCode() { return this.getState().hashCode() + this.getUser().hashCode() + this.getDate().hashCode(); } ... }

    Read the article

  • Java Alphabetize Algorithm Insertion sort vs Bubble Sort

    - by Chris Okyen
    I am supposed to "Develop a program that alphabetizes three strings. The program should allow the user to enter the three strings, and then display the strings in alphabetical order." It's instructed that I need to use the String library compareTo()/charAt()/toLowerCase() to make all the characters lowercase so the Lexicon comparison is also a alphabetical comparison. Input Pseudo Code: String input[3]; Scanner keyboard = new Scanner(System.in); System.out.println("Enter three strings: "); for(byte i = 0; i < 3; i++) input[i] = keyboard.next() The sorting would be Insertion Sort: 321 2 3 1 2 31 231 1 23 1 2 3 1 23 1 23 123 Bubble Sort 321 231 213 123 Which would be more efficient in this case? The bubble sort seems to be more efficient though they seem to have equal stats for worst best and avg case, but I read the Insertion Sort is quicker for small amounts of data like my case.

    Read the article

  • Simplifier le code de vos beans Java à l'aide de Commons Lang, Guava et Lombok, par Thierry Leriche-Dessirier

    Bonjour à tous, Je vous propose un article intitulé "Simplifier le code de vos beans Java à l'aide de Commons Lang, Guava et Lombok". Synopsis : Un bean classique, représentant un chien par exemple, peut vite peser des centaines de lignes quand on l'équipe avec les méthodes classiques et indispensables (constructeurs, getters, setters, equals, hashCode, toString, compareTo), même s'il possède peu d'attributs. Dans cet article, nous verrons comment mettre un tel cabot au régime et lui faire une beauté à l'aide de Commons Lang, Guava et Lombok. Nous en profiterons pour comparer ces bibliothèques entre elles et avec le code Java habituel, sans oublier celui qu'Eclipse génère. L'article est disponible ici :

    Read the article

  • specifying an object type at runtime

    - by lapin
    I've written a Vbo template class to work with opengl. I'd like to set the type from a config file at runtime. e.g. <vbo type="bump_vt" ... /> Vbo* pVbo = new Vbo(bump_vt, ...); Is there some way I can do this without a large if else block e.g. if( sType.compareTo("bump_vt") == 0 ) Vbo* pVbo = new Vbo(bump_vt, ...); else if ... I'm writing for multiple platforms in c++. thanks

    Read the article

  • How can I create a VBO of a type determined at runtime?

    - by lapin
    I've written a Vbo template class to work with OpenGL. I'd like to set the type from a config file at runtime. For example: <vbo type="bump_vt" ... /> Vbo* pVbo = new Vbo(bump_vt, ...); Is there some way I can do this without a large if-else block such as: if( sType.compareTo("bump_vt") == 0 ) Vbo* pVbo = new Vbo(bump_vt, ...); else if ... I'm writing for multiple platforms in C++.

    Read the article

  • Comparing strings with user-created string class

    - by meepz
    Basically, I created my own string class, mystring.h and mystring.c. What I want to do is write a function that compares two "strings" and then returns 1 first word is larger than the second, the opposite if word 2 is larger than word 1, and 0 if the two words are equal. What I have so far is this: int compareto(void * S1, void * S2){ String s1 = (String S1); String s2 = (String S2); int i, cs1 = 0, cs2 = 0; //cs1 is count of s1, cs2 is count of s2 while(s1->c[i] != '\0'){ //basically, while there is a word if(s1->c[i] < s2->c[i]) // if string 1 char is less than string 2 char cs2++; //add to string 2 count else (s1->c[i] > s2->c[i]) //vice versa cs1++; i++; } for my return I basically have if(cs1>cs2){ return 1; } else if(cs2 > cs1){ return 2; } return 0; here is mystring.h typedef struct mystring { char * c; int length; int (*sLength)(void * s); char (*charAt)(void * s, int i); int (*compareTo)(void * s1, void * s2); struct mystring * (*concat)(void * s1, void * s2); struct mystring * (*subString)(void * s, int begin, int end); void (*printS)(void * s); } string_t; typedef string_t * String; This does what I want, but only for unspecified order. What I want to do is search through my linked list for the last name. Ex. I have two entries in my linked list, smith and jones; Jones will be output as greater than smith, but alphabetically it isnt. (I'm using this to remove student entries from a generic link list I created) Any suggestions, all of my google searches involve using the library, so I've had no luck)

    Read the article

  • PriorityQueue update problems

    - by Bharat
    After going through a bunch of questions here on SO, I still have no idea what exactly is going wrong with my code and would appreciate some help. I'm trying to implement a priority queue based on f-costs for an A* algorithm, and while the algorithm works fine for short pathfinding distances, it seems to go wrong when there's an obstacle or when the distance between start and goal points is greater than about 30 squares (although sometimes it screws up for less too). while(!m_qOpenList.isEmpty()) { m_xCurrent=m_qOpenList.poll(); m_xCurrent.setBackground(Color.red); m_qClosedList.add(m_xCurrent); if(m_xCurrent.getStatus()==2) { System.out.println("Target Reached"); solved=true; break; } iX=m_xCurrent.getXCo(); iY=m_xCurrent.getYCo(); for(i=iX-1;i<=iX+1;i++) for(j=iY-1;j<=iY+1;j++) { if(i<0||j<0||i>m_iMazeX||j>m_iMazeX||(i==iX&&j==iY) || m_xNode[i][j].getStatus()==4|| m_qClosedList.contains(m_xNode[i][j])) continue; m_xNode[i][j].score(m_xCurrent,m_xGoal); m_qOpenList.add(m_xNode[i][j]); } } It's quite rudimentary as I'm just trying to get it to work for now. m_qOpenList is the PriorityQueue. The problem is that when I debug the program, at some point (near an obstacle), a Node with a fcost of say 84 has higher priority than a node with an fcost of 70. I am not attempting to modify the values once they're on the priority queue. You'll notice that I add at the end of the while loop (I read somewhere that the priorityqueue reorders itself when stuff is added to it), and poll right after that at the beginning. Status of 2 means the Node is the goal, and a status of 4 means that it is unwalkable. public int compareTo(Node o) { if(m_iF<o.m_iF) return -1; if(m_iF>o.m_iF) return 1; return 0; } And that's the compareTo function. Can you see a problem? =(

    Read the article

  • List<element> initialization fires "Process is terminated due to StackOverflowException"

    - by netmajor
    I have structs like below and when I do that initialization: ArrayList nodesMatrix = null; List<vertex> vertexMatrix = null; List<bool> odwiedzone = null; List<element> priorityQueue = null; vertexMatrix = new List<vertex>(nodesNr + 1); nodesMatrix = new ArrayList(nodesNr + 1); odwiedzone = new List<bool>(nodesNr + 1); priorityQueue = new List<element>(); arr.NodesMatrix = nodesMatrix; arr.VertexMatrix = vertexMatrix; arr.Odwiedzone = odwiedzone; arr.PriorityQueue = priorityQueue; //only here i have exception debuger fires Process is terminated due to StackOverflowException :/ Some idea why this collection fires this exception ? private struct arrays { ArrayList nodesMatrix; public ArrayList NodesMatrix { get { return nodesMatrix; } set { nodesMatrix = value; } } List<vertex> vertexMatrix; public List<vertex> VertexMatrix { get { return vertexMatrix; } set { vertexMatrix = value; } } List<bool> odwiedzone; public List<bool> Odwiedzone { get { return odwiedzone; } set { odwiedzone = value; } } public List<element> PriorityQueue { get { return PriorityQueue; } set { PriorityQueue = value; } } } public struct element : IComparable { public double priority { get { return priority; } set { priority = value; } } public int node { get { return node; } set { node = value; } } public element(double _prio, int _node) { priority = _prio; node = _node; } #region IComparable Members public int CompareTo(object obj) { element elem = (element)obj; return priority.CompareTo(elem.priority); } #endregion

    Read the article

  • C# what does the == operator do in detail?

    - by clamp
    in c# what does exactly happen in the background when you do a comparison with the "==" operator on two objects? does it just compare the addresses? or does it something like Equals() or CompareTo() ? PS: what about the "==" operator in java? does it behave the same?

    Read the article

  • Date Sorting - Latest to Oldest

    - by Erika Szabo
    Collections.sort(someList, new Comparator<SomeObject>() { public int compare(final SomeObject object1, final SomeObject object2) { return (object1.getSomeDate()).compareTo(object2.getSomeDate()); }} ); Would it give me the objects with latest dates meaning the list will contain the set of objects with latest date to oldest date?

    Read the article

  • State machines in C#

    - by Sir Psycho
    Hi, I'm trying to work out what's going on with this code. I have two threads iterating over the range and I'm trying to understand what is happening when the second thread calls GetEnumerator(). This line in particular (T current = start;), seems to spawn a new 'instance' in this method by the second thread. Seeing that there is only one instance of the DateRange class, I'm trying to understand why this works. Thanks in advance. class Program { static void Main(string[] args) { var daterange = new DateRange(DateTime.Now, DateTime.Now.AddDays(10), new TimeSpan(24, 0, 0)); var ts1 = new ThreadStart(delegate { foreach (var date in daterange) { Console.WriteLine("Thread " + Thread.CurrentThread.ManagedThreadId + " " + date); } }); var ts2 = new ThreadStart(delegate { foreach (var date in daterange) { Console.WriteLine("Thread " + Thread.CurrentThread.ManagedThreadId + " " + date); } }); Thread t1 = new Thread(ts1); Thread t2 = new Thread(ts2); t1.Start(); Thread.Sleep(4000); t2.Start(); Console.Read(); } } public class DateRange : Range<DateTime> { public DateTime Start { get; private set; } public DateTime End { get; private set; } public TimeSpan SkipValue { get; private set; } public DateRange(DateTime start, DateTime end, TimeSpan skip) : base(start, end) { SkipValue = skip; } public override DateTime GetNextElement(DateTime current) { return current.Add(SkipValue); } } public abstract class Range<T> : IEnumerable<T> where T : IComparable<T> { readonly T start; readonly T end; public Range(T start, T end) { if (start.CompareTo(end) > 0) throw new ArgumentException("Start value greater than end value"); this.start = start; this.end = end; } public abstract T GetNextElement(T currentElement); public IEnumerator<T> GetEnumerator() { T current = start; do { Thread.Sleep(1000); yield return current; current = GetNextElement(current); } while (current.CompareTo(end) < 1); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } }

    Read the article

  • C#: Abstract classes need to implement interfaces?

    - by bguiz
    My test code in C#: namespace DSnA { public abstract class Test : IComparable { } } Results in the following compiler error: error CS0535: 'DSnA.Test' does not implement interface member 'System.IComparable.CompareTo(object)' Since the class Test is an abstract class, why does the compiler require it to implement the interface? Shouldn't this requirement only be compulsory for concrete classes?

    Read the article

  • Find out what variable is throwing a NullPointerException programatically

    - by Hectoret
    I know I can find out if a variable is null in Java using these techniques: if (var==null) - too much work try { ... } catch (NullPointerException e) { ...} - it tells me what line is throwing the exception using the debugger - by hand, too slow Consider this line of code: if (this.superSL.items.get(name).getSource().compareTo(VIsualShoppingList.Source_EXTRA)==0) { I would like to know if there's a generic way to find out programatically what variable (not just the line) is throwing the NullPointerException in a certain area of code. In the example, knowing that

    Read the article

  • What is the best way to declare sorted association in grails domain classes ?

    - by fabien7474
    It seems that there are two different ways of declaring sorted associations in Grails : Method 1 (see here) using default sort order class Book { String title } class Author { static hasMany = [books : Book] static mapping = { books sort: "title"} } Method 2 (see here) using SortedSet class Book implements Comparable { String title int compareTo(obj) { title <=> obj.title } } class Author { SortedSet books static hasMany = [books : Book] } I am not sure which one to use and what is the difference (if any), pros and cons between using one against the other. I would appreciate any clarification. Thank you

    Read the article

  • Why is my List.Sort method in C# reversing the order of my list?

    - by Fiona Holder
    I have a list of items in a generic list: A1 (sort index 1) A2 (sort index 2) B1 (sort index 3) B2 (sort index 3) B3 (sort index 3) The comparator on them takes the form: this.sortIndex.CompareTo(other.sortIndex) When I do a List.Sort() on the list of items, I get the following order out: A1 A2 B3 B2 B1 It has obviously worked in the sense that the sort indexes are in the right order, but I really don't want it to be re-ordering the 'B' items. Is there any tweak I can make to my comparator to fix this?

    Read the article

  • Is there an existing delegate in the .NET Framework for comparison?

    - by Neil Barnwell
    The .NET framework provides a few handy general-use delegates for common tasks, such as Predicate<T> and EventHandler<T>. Is there a built-in delegate for the equivalent of CompareTo()? The signature might be something like this: delegate int Comparison<T>(T x, T y); This is to implement sorting in such a way that I can provide a lambda expression for the actual sort routine (ListView.ListViewItemSorter, specifically), so any other approaches welcome.

    Read the article

  • Collection, which method is used to authorize an add of an element ?

    - by Duke Vador
    We find a lot of concrete subclasses under Collection. While trying to add an element in a concrete collection, this collection will use a method to determine if it can accept to store the element (and eventually that this element is not already in the collection). It could use equals(), hashCode() or compareTo() of the element. Is it possible to find a summary about which method is used by each implementation of Collection ? Thanks a lot for your answers.

    Read the article

  • File sorting, Comparison method violates its general contract

    - by user2677383
    My file sorting comparator sometimes invoke java.lang.IllegalArgumentException in android app. I cannot figure out the reason. could you explain that? here is my code block: Comparator cc = new Comparator<File>() { @Override public int compare(File f1, File f2) { if (f1.isDirectory() && !f2.isDirectory()) { return 1; } if (f2.isDirectory() && !f1.isDirectory()) { return -1; } if ((f1.isFile() && f2.isFile()) || (f1.isDirectory() && f2.isDirectory())) { if (sort == 1) { return Util.compareFileName(f2.getName(), f1.getName()); } else if (sort == 2) { return (int) (f1.lastModified() - f2.lastModified()); } else if (sort == 3) { return (int) (f2.lastModified() - f1.lastModified()); } else if (sort == 4) { return (int) (f1.length() - f2.length()); } else if (sort == 5) { return (int) (f2.length() - f1.length()); } else return Util.compareFileName(f1.getName(), f2.getName()); } return f1.compareTo(f2); } }; Util.compareFileName is as followings: public static int compareFileName(String s1, String s2) { int thisMarker = 0; int thatMarker = 0; int s1Length = s1.length(); int s2Length = s2.length(); while (thisMarker < s1Length && thatMarker < s2Length) { String thisChunk = getChunk(s1, s1Length, thisMarker); thisMarker += thisChunk.length(); String thatChunk = getChunk(s2, s2Length, thatMarker); thatMarker += thatChunk.length(); // If both chunks contain numeric characters, sort them numerically int result = 0; if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0))) { // Simple chunk comparison by length. int thisChunkLength = thisChunk.length(); result = thisChunkLength - thatChunk.length(); // If equal, the first different number counts if (result == 0) { for (int i = 0; i < thisChunkLength; i++) { result = thisChunk.charAt(i) - thatChunk.charAt(i); if (result != 0) { return result; } } } } else { result = thisChunk.compareTo(thatChunk); } if (result != 0) return result; } return s1Length - s2Length; }

    Read the article

  • Parse CSS out from <style> elements

    - by awj
    Can someone tell me an efficient method of retrieving the CSS between tags on a page of markup in .NET? I've come up with a method which uses recursion, Split() and CompareTo() but is really long-winded, and I feel sure that there must be a far shorter (and more clever) method of doing the same. Please keep in mind that it is possible to have more than one element on a page, and that the element can be either or .

    Read the article

  • Implicit conversion causes stack overflow

    - by user44242
    The following code snippet worked perfectly, then after some code changes in different files, I've started getting stack overflows resulting from recursive invocation of the implicit conversion. Has this ever happened to anyone, and if so what's the fix. implicit def comparable2ordered[A <: Comparable[_]](x: A): Ordered[A] = new Ordered[A] with Proxy { val self = x def compare(y: A): Int = { self.compareTo(y) } }

    Read the article

  • Java Sorting "queue" list based on DateTime and Z Position (part of school project)

    - by Kuchinawa
    For a school project i have a list of 50k containers that arrive on a boat. These containers need to be sorted in a list in such a way that the earliest departure DateTimes are at the top and the containers above those above them. This list then gets used for a crane that picks them up in order. I started out with 2 Collection.sort() methods: 1st one to get them in the right XYZ order Collections.sort(containers, new Comparator<ContainerData>() { @Override public int compare(ContainerData contData1, ContainerData contData2) { return positionSort(contData1.getLocation(),contData2.getLocation()); } }); Then another one to reorder the dates while keeping the position in mind: Collections.sort(containers, new Comparator<ContainerData>() { @Override public int compare(ContainerData contData1, ContainerData contData2) { int c = contData1.getLeaveDateTimeFrom().compareTo(contData2.getLeaveDateTimeFrom()); int p = positionSort2(contData1.getLocation(), contData2.getLocation()); if(p != 0) c = p; return c; } }); But i never got this method to work.. What i got working now is rather quick and dirty and takes a long time to process (50seconds for all 50k): First a sort on DateTime: Collections.sort(containers, new Comparator<ContainerData>() { @Override public int compare(ContainerData contData1, ContainerData contData2) { return contData1.getLeaveDateTimeFrom().compareTo(contData2.getLeaveDateTimeFrom()); } }); Then a correction function that bumps top containers up: containers = stackCorrection(containers); private static List<ContainerData> stackCorrection(List<ContainerData> sortedContainerList) { for(int i = 0; i < sortedContainerList.size(); i++) { ContainerData current = sortedContainerList.get(i); // 5 = Max Stack (0 index) if(current.getLocation().getZ() < 5) { //Loop through possible containers above current for(int j = 5; j > current.getLocation().getZ(); --j) { //Search for container above for(int k = i + 1; k < sortedContainerList.size(); ++k) if(sortedContainerList.get(k).getLocation().getX() == current.getLocation().getX()) { if(sortedContainerList.get(k).getLocation().getY() == current.getLocation().getY()) { if(sortedContainerList.get(k).getLocation().getZ() == j) { //Found -> move container above current sortedContainerList.add(i, sortedContainerList.remove(k)); k = sortedContainerList.size(); i++; } } } } } } return sortedContainerList; } I would like to implement this in a better/faster way. So any hints are appreciated. :)

    Read the article

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