Search Results

Search found 163 results on 7 pages for 'linkedlist'.

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

  • Java Util Linked List - how to find next?

    - by drozzy
    When using Java LinkedList how do you find out the element's next or previous relationships? I mean, in a regular linked list I would do something like this: Node node1 = new Node(); Node node2 = new Node(); LinkedList list = new LinkedList(); list.add(node1); list.add(node2); //then my node1 will know who it's next is: assertEquals(node2, node1.next()); But in Java's LinkedList, the data does not seem to be modified. So how do I actually find out who the "next" (or "previous" in the case of doubly-linked lists) element is?

    Read the article

  • Cannot create an array of LinkedLists in Java...?

    - by kchau
    I'm working on a sparse matrix class that needs to use an array of LinkedLists to store the values of a matrix. Each element of the array (i.e. each LinkedList) represents a row of the matrix. And, each element in the LinkedLists represents a column and the stored value. In my class, I have a declaration of the array as: private LinkedList<IntegerNode>[] myMatrix; And, in my constructor for the SparseMatrix, I try to define: myMatrix = new LinkedList<IntegerNode>[numRows]; The error I end up getting is "Cannot create a generic array of LinkedList<IntegerNode>." So, I have two issues with this, 1) What am I doing wrong, and 2) Why is the type acceptable in the declaration for the array if it can't be created? Edit: IntegerNode is a class that I have created. And, all of my class files are packaged together.

    Read the article

  • convert object to in

    - by hoora
    hello! i'm beginner and i want to write a java code in eclipse! this program take two linkedlist of integers(for exp:a & b) and make a linkedlist (for exp:d) that every elements of it are summation of elements of that linkedlist! but i can't add this two element of linkedlist because these are Object!! please help me!! exp: a=[3,4,6,7,8] b=[4,3,7,5,3,2,1] d=[7,7,13,12,11,2,1] THANK YOU VERY VERY VERY MUCH!

    Read the article

  • 8-Puzzle Solution executes infinitely [migrated]

    - by Ashwin
    I am looking for a solution to 8-puzzle problem using the A* Algorithm. I found this project on the internet. Please see the files - proj1 and EightPuzzle. The proj1 contains the entry point for the program(the main() function) and EightPuzzle describes a particular state of the puzzle. Each state is an object of the 8-puzzle. I feel that there is nothing wrong in the logic. But it loops forever for these two inputs that I have tried : {8,2,7,5,1,6,3,0,4} and {3,1,6,8,4,5,7,2,0}. Both of them are valid input states. What is wrong with the code? Note For better viewing copy the code in a Notepad++ or some other text editor(which has the capability to recognize java source file) because there are lot of comments in the code. Since A* requires a heuristic, they have provided the option of using manhattan distance and a heuristic that calculates the number of misplaced tiles. And to ensure that the best heuristic is executed first, they have implemented a PriorityQueue. The compareTo() function is implemented in the EightPuzzle class. The input to the program can be changed by changing the value of p1d in the main() function of proj1 class. The reason I am telling that there exists solution for the two my above inputs is because the applet here solves them. Please ensure that you select 8-puzzle from teh options in the applet. EDITI gave this input {0,5,7,6,8,1,2,4,3}. It took about 10 seconds and gave a result with 26 moves. But the applet gave a result with 24 moves in 0.0001 seconds with A*. For quick reference I have pasted the the two classes without the comments : EightPuzzle import java.util.*; public class EightPuzzle implements Comparable <Object> { int[] puzzle = new int[9]; int h_n= 0; int hueristic_type = 0; int g_n = 0; int f_n = 0; EightPuzzle parent = null; public EightPuzzle(int[] p, int h_type, int cost) { this.puzzle = p; this.hueristic_type = h_type; this.h_n = (h_type == 1) ? h1(p) : h2(p); this.g_n = cost; this.f_n = h_n + g_n; } public int getF_n() { return f_n; } public void setParent(EightPuzzle input) { this.parent = input; } public EightPuzzle getParent() { return this.parent; } public int inversions() { /* * Definition: For any other configuration besides the goal, * whenever a tile with a greater number on it precedes a * tile with a smaller number, the two tiles are said to be inverted */ int inversion = 0; for(int i = 0; i < this.puzzle.length; i++ ) { for(int j = 0; j < i; j++) { if(this.puzzle[i] != 0 && this.puzzle[j] != 0) { if(this.puzzle[i] < this.puzzle[j]) inversion++; } } } return inversion; } public int h1(int[] list) // h1 = the number of misplaced tiles { int gn = 0; for(int i = 0; i < list.length; i++) { if(list[i] != i && list[i] != 0) gn++; } return gn; } public LinkedList<EightPuzzle> getChildren() { LinkedList<EightPuzzle> children = new LinkedList<EightPuzzle>(); int loc = 0; int temparray[] = new int[this.puzzle.length]; EightPuzzle rightP, upP, downP, leftP; while(this.puzzle[loc] != 0) { loc++; } if(loc % 3 == 0){ temparray = this.puzzle.clone(); temparray[loc] = temparray[loc + 1]; temparray[loc + 1] = 0; rightP = new EightPuzzle(temparray, this.hueristic_type, this.g_n + 1); rightP.setParent(this); children.add(rightP); }else if(loc % 3 == 1){ //add one child swaps with right temparray = this.puzzle.clone(); temparray[loc] = temparray[loc + 1]; temparray[loc + 1] = 0; rightP = new EightPuzzle(temparray, this.hueristic_type, this.g_n + 1); rightP.setParent(this); children.add(rightP); //add one child swaps with left temparray = this.puzzle.clone(); temparray[loc] = temparray[loc - 1]; temparray[loc - 1] = 0; leftP = new EightPuzzle(temparray, this.hueristic_type, this.g_n + 1); leftP.setParent(this); children.add(leftP); }else if(loc % 3 == 2){ // add one child swaps with left temparray = this.puzzle.clone(); temparray[loc] = temparray[loc - 1]; temparray[loc - 1] = 0; leftP = new EightPuzzle(temparray, this.hueristic_type, this.g_n + 1); leftP.setParent(this); children.add(leftP); } if(loc / 3 == 0){ //add one child swaps with lower temparray = this.puzzle.clone(); temparray[loc] = temparray[loc + 3]; temparray[loc + 3] = 0; downP = new EightPuzzle(temparray, this.hueristic_type, this.g_n + 1); downP.setParent(this); children.add(downP); }else if(loc / 3 == 1 ){ //add one child, swap with upper temparray = this.puzzle.clone(); temparray[loc] = temparray[loc - 3]; temparray[loc - 3] = 0; upP = new EightPuzzle(temparray, this.hueristic_type, this.g_n + 1); upP.setParent(this); children.add(upP); //add one child, swap with lower temparray = this.puzzle.clone(); temparray[loc] = temparray[loc + 3]; temparray[loc + 3] = 0; downP = new EightPuzzle(temparray, this.hueristic_type, this.g_n + 1); downP.setParent(this); children.add(downP); }else if (loc / 3 == 2 ){ //add one child, swap with upper temparray = this.puzzle.clone(); temparray[loc] = temparray[loc - 3]; temparray[loc - 3] = 0; upP = new EightPuzzle(temparray, this.hueristic_type, this.g_n + 1); upP.setParent(this); children.add(upP); } return children; } public int h2(int[] list) // h2 = the sum of the distances of the tiles from their goal positions // for each item find its goal position // calculate how many positions it needs to move to get into that position { int gn = 0; int row = 0; int col = 0; for(int i = 0; i < list.length; i++) { if(list[i] != 0) { row = list[i] / 3; col = list[i] % 3; row = Math.abs(row - (i / 3)); col = Math.abs(col - (i % 3)); gn += row; gn += col; } } return gn; } public String toString() { String x = ""; for(int i = 0; i < this.puzzle.length; i++){ x += puzzle[i] + " "; if((i + 1) % 3 == 0) x += "\n"; } return x; } public int compareTo(Object input) { if (this.f_n < ((EightPuzzle) input).getF_n()) return -1; else if (this.f_n > ((EightPuzzle) input).getF_n()) return 1; return 0; } public boolean equals(EightPuzzle test){ if(this.f_n != test.getF_n()) return false; for(int i = 0 ; i < this.puzzle.length; i++) { if(this.puzzle[i] != test.puzzle[i]) return false; } return true; } public boolean mapEquals(EightPuzzle test){ for(int i = 0 ; i < this.puzzle.length; i++) { if(this.puzzle[i] != test.puzzle[i]) return false; } return true; } } proj1 import java.util.*; public class proj1 { /** * @param args */ public static void main(String[] args) { int[] p1d = {1, 4, 2, 3, 0, 5, 6, 7, 8}; int hueristic = 2; EightPuzzle start = new EightPuzzle(p1d, hueristic, 0); int[] win = { 0, 1, 2, 3, 4, 5, 6, 7, 8}; EightPuzzle goal = new EightPuzzle(win, hueristic, 0); astar(start, goal); } public static void astar(EightPuzzle start, EightPuzzle goal) { if(start.inversions() % 2 == 1) { System.out.println("Unsolvable"); return; } // function A*(start,goal) // closedset := the empty set // The set of nodes already evaluated. LinkedList<EightPuzzle> closedset = new LinkedList<EightPuzzle>(); // openset := set containing the initial node // The set of tentative nodes to be evaluated. priority queue PriorityQueue<EightPuzzle> openset = new PriorityQueue<EightPuzzle>(); openset.add(start); while(openset.size() > 0){ // x := the node in openset having the lowest f_score[] value EightPuzzle x = openset.peek(); // if x = goal if(x.mapEquals(goal)) { // return reconstruct_path(came_from, came_from[goal]) Stack<EightPuzzle> toDisplay = reconstruct(x); System.out.println("Printing solution... "); System.out.println(start.toString()); print(toDisplay); return; } // remove x from openset // add x to closedset closedset.add(openset.poll()); LinkedList <EightPuzzle> neighbor = x.getChildren(); // foreach y in neighbor_nodes(x) while(neighbor.size() > 0) { EightPuzzle y = neighbor.removeFirst(); // if y in closedset if(closedset.contains(y)){ // continue continue; } // tentative_g_score := g_score[x] + dist_between(x,y) // // if y not in openset if(!closedset.contains(y)){ // add y to openset openset.add(y); // } // } // } } public static void print(Stack<EightPuzzle> x) { while(!x.isEmpty()) { EightPuzzle temp = x.pop(); System.out.println(temp.toString()); } } public static Stack<EightPuzzle> reconstruct(EightPuzzle winner) { Stack<EightPuzzle> correctOutput = new Stack<EightPuzzle>(); while(winner.getParent() != null) { correctOutput.add(winner); winner = winner.getParent(); } return correctOutput; } }

    Read the article

  • templete class c++

    - by inna karpasas
    hi! i try to design a templete for my universty project. i wrote the follwing cod: #ifndef _LinkedList_H_ #define _LinkedList_H_ #include "Link.h" #include <ostream> template <class L>//error one class LinkedList { private: Link<L> *pm_head; Link<L> * pm_tail; int m_numOfElements; Link<L>* FindLink(L * dataToFind); public: LinkedList(); ~LinkedList(); int GetNumOfElements(){return m_numOfElements;} bool Add( L * data); L *FindData(L * data); template <class L> friend ostream & operator<<(ostream& os,const LinkedList<L> listToprint);//error two L* GetDataOnTop(); bool RemoveFromHead(); L* Remove(L * toRemove); this templete uses the link class templete #ifndef _Link_H_ #define _Link_H_ template <class T>//error 3 class Link { private: T* m_data; Link* m_next; Link* m_prev; public: Link(T* data); ~Link(void); bool Link::operator ==(const Link& other)const; /*getters*/ Link* GetNext()const {return m_next;} Link* GetPrev()const {return m_prev;} T* GetData()const {return m_data;} //setters void SetNext(Link* next) {m_next = next;} void SetPrev(Link* prev) {m_prev = prev;} void SetData(T* data) {m_data = data;} }; error one: shadows template parm class L' error two:declaration ofclass L' error three: shadows template parm `class T' i dont understand what is the problem. i can relly usr your help thank you :)

    Read the article

  • Converting "A* Search" code from C++ to Java [on hold]

    - by mr5
    Updated! I get this code from this site It's A* Search Algorithm(finding shortest path with heuristics) I modify most of variable names and some if conditions from the original version to satisfy my syntactic taste. It works in C++ (as I can't see any trouble with it) but fails in Java version. Java Code: String findPath(int startX, int startY, int finishX, int finishY) { @SuppressWarnings("unchecked") LinkedList<Node>[] nodeList = (LinkedList<Node>[]) new LinkedList<?>[2]; nodeList[0] = new LinkedList<Node>(); nodeList[1] = new LinkedList<Node>(); Node n0; Node m0; int nlIndex = 0; // queueList index // reset the node maps for(int y = 0;y < ROW_COUNT; ++y) { for(int x = 0;x < COL_COUNT; ++x) { close_nodes_map[y][x] = 0; open_nodes_map[y][x] = 0; } } // create the start node and push into list of open nodes n0 = new Node( startX, startY, 0, 0 ); n0.updatePriority( finishX, finishY ); nodeList[nlIndex].push( n0 ); open_nodes_map[startY][startX] = n0.getPriority(); // mark it on the open nodes map // A* search while( !nodeList[nlIndex].isEmpty() ) { LinkedList<Node> pq = nodeList[nlIndex]; // get the current node w/ the highest priority // from the list of open nodes n0 = new Node( pq.peek().getX(), pq.peek().getY(), pq.peek().getIterCount(), pq.peek().getPriority()); int x = n0.getX(); int y = n0.getY(); nodeList[nlIndex].pop(); // remove the node from the open list open_nodes_map[y][x] = 0; // mark it on the closed nodes map close_nodes_map[y][x] = 1; // quit searching when the goal state is reached //if((*n0).estimate(finishX, finishY) == 0) if( x == finishX && y == finishY ) { // generate the path from finish to start // by following the directions String path = ""; while( !( x == startX && y == startY) ) { int j = dir_map[y][x]; int c = '0' + ( j + Node.DIRECTION_COUNT / 2 ) % Node.DIRECTION_COUNT; path = (char)c + path; x += DIR_X[j]; y += DIR_Y[j]; } return path; } // generate moves (child nodes) in all possible directions for(int i = 0; i < Node.DIRECTION_COUNT; ++i) { int xdx = x + DIR_X[i]; int ydy = y + DIR_Y[i]; // boundary check if (!(xdx >= 0 && xdx < COL_COUNT && ydy >= 0 && ydy < ROW_COUNT)) continue; if ( ( gridMap.getData( ydy, xdx ) == GridMap.WALKABLE || gridMap.getData( ydy, xdx ) == GridMap.FINISH) && close_nodes_map[ydy][xdx] != 1 ) { // generate a child node m0 = new Node( xdx, ydy, n0.getIterCount(), n0.getPriority() ); m0.nextLevel( i ); m0.updatePriority( finishX, finishY ); // if it is not in the open list then add into that if( open_nodes_map[ydy][xdx] == 0 ) { open_nodes_map[ydy][xdx] = m0.getPriority(); nodeList[nlIndex].push( m0 ); // mark its parent node direction dir_map[ydy][xdx] = ( i + Node.DIRECTION_COUNT / 2 ) % Node.DIRECTION_COUNT; } else if( open_nodes_map[ydy][xdx] > m0.getPriority() ) { // update the priority info open_nodes_map[ydy][xdx] = m0.getPriority(); // update the parent direction info dir_map[ydy][xdx] = ( i + Node.DIRECTION_COUNT / 2 ) % Node.DIRECTION_COUNT; // replace the node // by emptying one queueList to the other one // except the node to be replaced will be ignored // and the new node will be pushed in instead while( !(nodeList[nlIndex].peek().getX() == xdx && nodeList[nlIndex].peek().getY() == ydy ) ) { nodeList[1 - nlIndex].push( nodeList[nlIndex].pop() ); } nodeList[nlIndex].pop(); // remove the wanted node // empty the larger size queueList to the smaller one if( nodeList[nlIndex].size() > nodeList[ 1 - nlIndex ].size() ) nlIndex = 1 - nlIndex; while( !nodeList[nlIndex].isEmpty() ) { nodeList[1 - nlIndex].push( nodeList[nlIndex].pop() ); } nlIndex = 1 - nlIndex; nodeList[nlIndex].push( m0 ); // add the better node instead } } } } return ""; // no route found } Output1: Legends . = PATH ? = START X = FINISH 3,2,1 = OBSTACLES (Misleading path) Output2: Changing these lines: n0 = new Node( a, b, c, d ); m0 = new Node( e, f, g, h ); to n0.set( a, b, c, d ); m0.set( e, f, g, h ); I get (I'm really confused) C++ Code: std::string A_Star::findPath(int startX, int startY, int finishX, int finishY) { typedef std::queue<Node> List_Container; List_Container nodeList[2]; // list of open (not-yet-tried) nodes Node n0; Node m0; int pqIndex = 0; // nodeList index // reset the node maps for(int y = 0;y < ROW_COUNT; ++y) { for(int x = 0;x < COL_COUNT; ++x) { close_nodes_map[y][x] = 0; open_nodes_map[y][x] = 0; } } // create the start node and push into list of open nodes n0 = Node( startX, startY, 0, 0 ); n0.updatePriority( finishX, finishY ); nodeList[pqIndex].push( n0 ); open_nodes_map[startY][startX] = n0.getPriority(); // mark it on the open nodes map // A* search while( !nodeList[pqIndex].empty() ) { List_Container &pq = nodeList[pqIndex]; // get the current node w/ the highest priority // from the list of open nodes n0 = Node( pq.front().getX(), pq.front().getY(), pq.front().getIterCount(), pq.front().getPriority()); int x = n0.getX(); int y = n0.getY(); nodeList[pqIndex].pop(); // remove the node from the open list open_nodes_map[y][x] = 0; // mark it on the closed nodes map close_nodes_map[y][x] = 1; // quit searching when the goal state is reached //if((*n0).estimate(finishX, finishY) == 0) if( x == finishX && y == finishY ) { // generate the path from finish to start // by following the directions std::string path = ""; while( !( x == startX && y == startY) ) { int j = dir_map[y][x]; char c = '0' + ( j + DIRECTION_COUNT / 2 ) % DIRECTION_COUNT; path = c + path; x += DIR_X[j]; y += DIR_Y[j]; } return path; } // generate moves (child nodes) in all possible directions for(int i = 0; i < DIRECTION_COUNT; ++i) { int xdx = x + DIR_X[i]; int ydy = y + DIR_Y[i]; // boundary check if (!( xdx >= 0 && xdx < COL_COUNT && ydy >= 0 && ydy < ROW_COUNT)) continue; if ( ( pGrid->getData(ydy,xdx) == WALKABLE || pGrid->getData(ydy, xdx) == FINISH) && close_nodes_map[ydy][xdx] != 1 ) { // generate a child node m0 = Node( xdx, ydy, n0.getIterCount(), n0.getPriority() ); m0.nextLevel( i ); m0.updatePriority( finishX, finishY ); // if it is not in the open list then add into that if( open_nodes_map[ydy][xdx] == 0 ) { open_nodes_map[ydy][xdx] = m0.getPriority(); nodeList[pqIndex].push( m0 ); // mark its parent node direction dir_map[ydy][xdx] = ( i + DIRECTION_COUNT / 2 ) % DIRECTION_COUNT; } else if( open_nodes_map[ydy][xdx] > m0.getPriority() ) { // update the priority info open_nodes_map[ydy][xdx] = m0.getPriority(); // update the parent direction info dir_map[ydy][xdx] = ( i + DIRECTION_COUNT / 2 ) % DIRECTION_COUNT; // replace the node // by emptying one nodeList to the other one // except the node to be replaced will be ignored // and the new node will be pushed in instead while ( !( nodeList[pqIndex].front().getX() == xdx && nodeList[pqIndex].front().getY() == ydy ) ) { nodeList[1 - pqIndex].push( nodeList[pqIndex].front() ); nodeList[pqIndex].pop(); } nodeList[pqIndex].pop(); // remove the wanted node // empty the larger size nodeList to the smaller one if( nodeList[pqIndex].size() > nodeList[ 1 - pqIndex ].size() ) pqIndex = 1 - pqIndex; while( !nodeList[pqIndex].empty() ) { nodeList[1-pqIndex].push(nodeList[pqIndex].front()); nodeList[pqIndex].pop(); } pqIndex = 1 - pqIndex; nodeList[pqIndex].push( m0 ); // add the better node instead } } } } return ""; // no route found } Output: Legends . = PATH ? = START X = FINISH 3,2,1 = OBSTACLES (Just right) From what I read about Java's documentation, I came up with the conclusion: C++'s std::queue<T>::front() == Java's LinkedList<T>.peek() Java's LinkedList<T>.pop() == C++'s std::queue<T>::front() + std::queue<T>::pop() What might I be missing in my Java version? In what way does it became different algorithmically from the C++ version?

    Read the article

  • learning C++ from java, trying to make a linked list.

    - by kyeana
    I just started learning c++ (coming from java) and am having some serious problems with doing anything :P Currently, i am attempting to make a linked list, but must be doing something stupid cause i keep getting "void value not ignored as it ought to be" compile errors (i have it marked where it is throwing it bellow). If anyone could help me with what im doing wrong, i would be very grateful :) Also, I am not used to having the choice of passing by reference, address, or value, and memory management in general (currently i have all my nodes and the data declared on the heap). If anyone has any general advice for me, i also wouldn't complain :P Key code from LinkedListNode.cpp LinkedListNode::LinkedListNode() { //set next and prev to null pData=0; //data needs to be a pointer so we can set it to null for //for the tail and head. pNext=0; pPrev=0; } /* * Sets the 'next' pointer to the memory address of the inputed reference. */ void LinkedListNode::SetNext(LinkedListNode& _next) { pNext=&_next; } /* * Sets the 'prev' pointer to the memory address of the inputed reference. */ void LinkedListNode::SetPrev(LinkedListNode& _prev) { pPrev=&_prev; } //rest of class Key code from LinkedList.cpp #include "LinkedList.h" LinkedList::LinkedList() { // Set head and tail of linked list. pHead = new LinkedListNode(); pTail = new LinkedListNode(); /* * THIS IS WHERE THE ERRORS ARE. */ *pHead->SetNext(*pTail); *pTail->SetPrev(*pHead); } //rest of class

    Read the article

  • Linked List exercise, what am I doing wrong?

    - by Sean Ochoa
    Hey all. I'm doing a linked list exercise that involves dynamic memory allocation, pointers, classes, and exceptions. Would someone be willing to critique it and tell me what I did wrong and what I should have done better both with regards to style and to those subjects I listed above? /* Linked List exercise */ #include <iostream> #include <exception> #include <string> using namespace std; class node{ public: node * next; int * data; node(const int i){ data = new int; *data = i; } node& operator=(node n){ *data = *(n.data); } ~node(){ delete data; } }; class linkedList{ public: node * head; node * tail; int nodeCount; linkedList(){ head = NULL; tail = NULL; } ~linkedList(){ while (head){ node* t = head->next; delete head; if (t) head = t; } } void add(node * n){ if (!head) { head = n; head->next = NULL; tail = head; nodeCount = 0; }else { node * t = head; while (t->next) t = t->next; t->next = n; n->next = NULL; nodeCount++; } } node * operator[](const int &i){ if ((i >= 0) && (i < nodeCount)) throw new exception("ERROR: Invalid index on linked list.", -1); node *t = head; for (int x = i; x < nodeCount; x++) t = t->next; return t; } void print(){ if (!head) return; node * t = head; string collection; cout << "["; int c = 0; if (!t->next) cout << *(t->data); else while (t->next){ cout << *(t->data); c++; if (t->next) t = t->next; if (c < nodeCount) cout << ", "; } cout << "]" << endl; } }; int main (const int & argc, const char * argv[]){ try{ linkedList * myList = new linkedList; for (int x = 0; x < 10; x++) myList->add(new node(x)); myList->print(); }catch(exception &ex){ cout << ex.what() << endl; return -1; } return 0; }

    Read the article

  • Unresolved External Symbol? error lnk2019

    - by jay
    Hello, I was wondering if anyone knew what this error meant. Thanks error LNK2019: unresolved external symbol "public: void __thiscall LinkedList,class std::allocator ::LocItem *::decreasekey(class PriorityList,class std::allocator ::LocItem * const &)" (?decreasekey@?$LinkedList@HPAVLocItem@?$PriorityList@HV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@@@@QAEXABQAVLocItem@?$PriorityList@HV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@@@Z) referenced in function "public: void __thiscall PriorityList,class std::allocator ::decreasekey(class PriorityList,class std::allocator ::Locator)" (?decreasekey@?$PriorityList@HV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@@QAEXVLocator@1@@Z)

    Read the article

  • Java - Collections.sort() performance

    - by msr
    Hello, Im using Collections.sort() to sort a LinkedList whose elements implements Comparable interface, so they are sorted in a natural order. In the javadoc documentation its said this method uses mergesort algorithm wich has n*log(n) performance. My question is if there is a more efficient algorithm to sort my LinkedList? The size of that list could be very high and sort will be also very frequent. Thanks!

    Read the article

  • startsWith using error in java

    - by user1838839
    defined variable: LinkedList list1=new LinkedList(); Object get() in list1 obtains a node of list1 Object remove() in list1 deletes a node of list1 count() is length of list1 for(int i=1;i<list1.count();i++){ if(list1.get(i).startsWith('"',0)) //Error here list1.remove(i); } Error: cannot find symbol symbol: method charAt(int) location: class Object how to fix this problem? I would like to delete the node in list1 which starts with (").

    Read the article

  • What is the fastest collection in c# to implement a prioritizing queue?

    - by Nathan Smith
    I need to implement a queue for messages on a game server so it needs to as fast as possible. The queue will have a maxiumem size. I need to prioritize messages once the queue is full by working backwards and removing a lower priority message (if one exists) before adding the new message. The appliation is asynchronous so access to the queue needs to be locked. I'm currently implementing it using a LinkedList as the underlying storage but have concerns that searching and removing nodes will keep it locked for too long. Heres the basic code I have at the moment: public class ActionQueue { private LinkedList<ClientAction> _actions = new LinkedList<ClientAction>(); private int _maxSize; /// <summary> /// Initializes a new instance of the ActionQueue class. /// </summary> public ActionQueue(int maxSize) { _maxSize = maxSize; } public int Count { get { return _actions.Count; } } public void Enqueue(ClientAction action) { lock (_actions) { if (Count < _maxSize) _actions.AddLast(action); else { LinkedListNode<ClientAction> node = _actions.Last; while (node != null) { if (node.Value.Priority < action.Priority) { _actions.Remove(node); _actions.AddLast(action); break; } } } } } public ClientAction Dequeue() { ClientAction action = null; lock (_actions) { action = _actions.First.Value; _actions.RemoveFirst(); } return action; } }

    Read the article

  • How do I remove implementing types from GWT’s Serialization Policy?

    - by Bluu
    The opposite of this question: http://stackoverflow.com/questions/138099/how-do-i-add-a-type-to-gwts-serialization-policy-whitelist GWT is adding undesired types to the serialization policy and bloating my JS. How do I trim my GWT whitelist by hand? Or should I at all? For example, if I put the interface List on a GWT RPC service class, GWT has to generate Javascript that handles ArrayList, LinkedList, Stack, Vector, ... even though my team knows we're only ever going to return an ArrayList. I could just make the method's return type ArrayList, but I like relying on an interface rather than a specific implementation. After all, maybe one day we will switch it up and return e.g. a LinkedList. In that case, I'd like to force the GWT serialization policy to compile for only ArrayList and LinkedList. No Stacks or Vectors. These implicit restrictions have one huge downside I can think of: a new member of the team starts returning Vectors, which will be a runtime error. So besides the question in the title, what is your experience designing around this?

    Read the article

  • How can I bind a List as ItemSource to ListView in XAML?

    - by Jonas
    I'm learning WPF and would like to have a collection similar to a LinkedList, to where I can add and remove strings. And I want to have a ListView that listen to that collection with databinding. How can I do bind a simple list collection to a ListView in XAML? My idea (not working) is something like this: <Window x:Class="TestApp.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <LinkedList x:Key="myList"></LinkedList> //Wrong <Window.Resources> <Grid> <ListView Height="100" HorizontalAlignment="Left" Margin="88,134,0,0" Name="listView1" VerticalAlignment="Top" Width="120" ItemsSource="{Binding Source={StaticResource myList}}"/> //Wrong </Grid> </Window> All my code (updated version, not working): <Window x:Class="TestApp.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <TextBox Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" /> <Button Content="Button" Height="23" HorizontalAlignment="Right" Margin="0,12,290,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" /> <ListView Height="100" HorizontalAlignment="Left" Margin="88,134,0,0" Name="listView1" VerticalAlignment="Top" Width="120" ItemsSource="{Binding myList}"/> </Grid> </Window> C#-code: namespace TestApp { public partial class MainWindow : Window { ObservableCollection<string> myList = new ObservableCollection<string>(); public MainWindow() { InitializeComponent(); myList.Add("first string"); } private void button1_Click(object sender, RoutedEventArgs e) { myList.Add(textBox1.Text); textBox1.Text = myList.Count+"st"; } } }

    Read the article

  • C++ compiler unable to find function (namespace related)

    - by CS student
    I'm working in Visual Studio 2008 on a C++ programming assignment. We were supplied with files that define the following namespace hierarchy (the names are just for the sake of this post, I know "namespace XYZ-NAMESPACE" is redundant): (MAIN-NAMESPACE){ a bunch of functions/classes I need to implement... (EXCEPTIONS-NAMESPACE){ a bunch of exceptions } (POINTER-COLLECTIONS-NAMESPACE){ Set and LinkedList classes, plus iterators } } The MAIN-NAMESPACE contents are split between a bunch of files, and for some reason which I don't understand the operator<< for both Set and LinkedList is entirely outside of the MAIN-NAMESPACE (but within Set and LinkedList's header file). Here's the Set version: template<typename T> std::ostream& operator<<(std::ostream& os, const MAIN-NAMESPACE::POINTER-COLLECTIONS-NAMESPACE::Set<T>& set) Now here's the problem: I have the following data structure: Set A Set B Set C double num It's defined to be in a class within MAIN-NAMESPACE. When I create an instance of the class, and try to print one of the sets, it tells me that: error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const MAIN-NAMESPACE::POINTER-COLLECTIONS-NAMESPACE::Set' (or there is no acceptable conversion) However, if I just write a main() function, and create Set A, fill it up, and use the operator- it works. Any idea what is the problem? (note: I tried any combination of using and include I could think of).

    Read the article

  • Properly Configured Rsyslog on CentOS

    - by Gaia
    I'm trying to configure Rsyslog 5.8.10 on CentOS 6.4 to send Apache's error and access logs to a remote server. It's working, but I have a couple questions. A) I would like to use as few queues (and resources) as possible. I send error logs to server A, send access logs to server A, send both logs in one stream to server B. Should I specify one queue per external service (2 queues) or one queue per stream (3 queues, as I have now)? This is what I have: $ActionResumeInterval 10 $ActionQueueSize 100000 $ActionQueueDiscardMark 97500 $ActionQueueHighWaterMark 80000 $ActionQueueType LinkedList $ActionQueueFileName logglyaccessqueue $ActionQueueCheckpointInterval 100 $ActionQueueMaxDiskSpace 1g $ActionResumeRetryCount -1 $ActionQueueSaveOnShutdown on $ActionQueueTimeoutEnqueue 10 $ActionQueueDiscardSeverity 0 if $syslogtag startswith 'www-access' then @@logs-01.loggly.com:514;logglyaccess $ActionResumeInterval 10 $ActionQueueSize 100000 $ActionQueueDiscardMark 97500 $ActionQueueHighWaterMark 80000 $ActionQueueType LinkedList $ActionQueueFileName logglyerrorsqueue $ActionQueueCheckpointInterval 100 $ActionQueueMaxDiskSpace 1g $ActionResumeRetryCount -1 $ActionQueueSaveOnShutdown on $ActionQueueTimeoutEnqueue 10 $ActionQueueDiscardSeverity 0 if $syslogtag startswith 'www-errors' then @@logs-01.loggly.com:514;logglyerrors $DefaultNetstreamDriverCAFile /etc/syslog.papertrail.crt # trust these CAs $ActionSendStreamDriver gtls # use gtls netstream driver $ActionSendStreamDriverMode 1 # require TLS $ActionSendStreamDriverAuthMode x509/name # authenticate by hostname $ActionResumeInterval 10 $ActionQueueSize 100000 $ActionQueueDiscardMark 97500 $ActionQueueHighWaterMark 80000 $ActionQueueType LinkedList $ActionQueueFileName papertrailqueue $ActionQueueCheckpointInterval 100 $ActionQueueMaxDiskSpace 1g $ActionResumeRetryCount -1 $ActionQueueSaveOnShutdown on $ActionQueueTimeoutEnqueue 10 $ActionQueueDiscardSeverity 0 *.* @@logs.papertrailapp.com:XXXXX;papertrailstandard & ~ B) Does a queue block get used over and over by every send action that follows it or only by the first one or only until it encounters a send followed by a discard action (~)? C) How do I reset a queue block so that an upcoming send action does not use a queue at all? D) Does a TLS block get used over and over by every send action that follows it or only by the first one or only until it encounters a send followed by a discard action (~)? E) How do I reset a TLS block so that an upcoming send action does not use TLS at all? F) If I run rsyslog -N1 I get: rsyslogd -N1 rsyslogd: version 5.8.10, config validation run (level 1), master config /etc/rsyslog.conf rsyslogd: WARNING: rsyslogd is running in compatibility mode. Automatically generated config directives may interfer with your rsyslog.conf settings. We suggest upgrading your config and adding -c5 as the first rsyslogd option. rsyslogd: Warning: backward compatibility layer added to following directive to rsyslog.conf: ModLoad immark rsyslogd: Warning: backward compatibility layer added to following directive to rsyslog.conf: MarkMessagePeriod 1200 rsyslogd: Warning: backward compatibility layer added to following directive to rsyslog.conf: ModLoad imuxsock rsyslogd: End of config validation run. Bye. Where do I place the -c5 so that it doesnt run in compatibility mode anymore?

    Read the article

  • Proper method to update and draw from game loop?

    - by Lost_Soul
    Recently I've took up the challenge for myself to create a basic 2d side scrolling monster truck game for my little brother. Which seems easy enough in theory. After working with XNA it seems strange jumping into Java (which is what I plan to program it in). Inside my game class I created a private class called GameLoop that extends from Runnable, then in the overridden run() method I made a while loop that handles time and such and I implemented a targetFPS for drawing as well. The loop looks like this: @Override public void run() { long fpsTime = 0; gameStart = System.currentTimeMillis(); lastTime = System.currentTimeMillis(); while(game.isGameRunning()) { currentTime = System.currentTimeMillis(); long ellapsedTime = currentTime - lastTime; if(mouseState.leftIsDown) { que.add(new Dot(mouseState.getPosition())); } entities.addAll(que); game.updateGame(ellapsedTime); fpsTime += ellapsedTime; if(fpsTime >= (1000 / targetedFPS)) { game.drawGame(ellapsedTime); } lastTime = currentTime; } The problem I've ran into is adding of entities after a click. I made a class that has another private class that extends MouseListener and MouseMotionListener then on changes I have it set a few booleans to tell me if the mouse is pressed or not which seems to work great but when I add the entity it throws a CME (Concurrent Modification Exception) sometimes. I have all the entities stored in a LinkedList so later I tried adding a que linkedlist where I later add the que to the normal list in the update loop. I think this would work fine if it was just the update method in the gameloop but with the repaint() method (called inside game.drawGame() method) it throws the CME. The only other thing is that I'm currently drawing directly from the overridden paintComponent() method in a custom class that extends JPanel. Maybe there is a better way to go about this? As well as fix my CME? Thanks in advance!!!

    Read the article

  • C#/.NET Fundamentals: Choosing the Right Collection Class

    - by James Michael Hare
    The .NET Base Class Library (BCL) has a wide array of collection classes at your disposal which make it easy to manage collections of objects. While it's great to have so many classes available, it can be daunting to choose the right collection to use for any given situation. As hard as it may be, choosing the right collection can be absolutely key to the performance and maintainability of your application! This post will look at breaking down any confusion between each collection and the situations in which they excel. We will be spending most of our time looking at the System.Collections.Generic namespace, which is the recommended set of collections. The Generic Collections: System.Collections.Generic namespace The generic collections were introduced in .NET 2.0 in the System.Collections.Generic namespace. This is the main body of collections you should tend to focus on first, as they will tend to suit 99% of your needs right up front. It is important to note that the generic collections are unsynchronized. This decision was made for performance reasons because depending on how you are using the collections its completely possible that synchronization may not be required or may be needed on a higher level than simple method-level synchronization. Furthermore, concurrent read access (all writes done at beginning and never again) is always safe, but for concurrent mixed access you should either synchronize the collection or use one of the concurrent collections. So let's look at each of the collections in turn and its various pros and cons, at the end we'll summarize with a table to help make it easier to compare and contrast the different collections. The Associative Collection Classes Associative collections store a value in the collection by providing a key that is used to add/remove/lookup the item. Hence, the container associates the value with the key. These collections are most useful when you need to lookup/manipulate a collection using a key value. For example, if you wanted to look up an order in a collection of orders by an order id, you might have an associative collection where they key is the order id and the value is the order. The Dictionary<TKey,TVale> is probably the most used associative container class. The Dictionary<TKey,TValue> is the fastest class for associative lookups/inserts/deletes because it uses a hash table under the covers. Because the keys are hashed, the key type should correctly implement GetHashCode() and Equals() appropriately or you should provide an external IEqualityComparer to the dictionary on construction. The insert/delete/lookup time of items in the dictionary is amortized constant time - O(1) - which means no matter how big the dictionary gets, the time it takes to find something remains relatively constant. This is highly desirable for high-speed lookups. The only downside is that the dictionary, by nature of using a hash table, is unordered, so you cannot easily traverse the items in a Dictionary in order. The SortedDictionary<TKey,TValue> is similar to the Dictionary<TKey,TValue> in usage but very different in implementation. The SortedDictionary<TKey,TValye> uses a binary tree under the covers to maintain the items in order by the key. As a consequence of sorting, the type used for the key must correctly implement IComparable<TKey> so that the keys can be correctly sorted. The sorted dictionary trades a little bit of lookup time for the ability to maintain the items in order, thus insert/delete/lookup times in a sorted dictionary are logarithmic - O(log n). Generally speaking, with logarithmic time, you can double the size of the collection and it only has to perform one extra comparison to find the item. Use the SortedDictionary<TKey,TValue> when you want fast lookups but also want to be able to maintain the collection in order by the key. The SortedList<TKey,TValue> is the other ordered associative container class in the generic containers. Once again SortedList<TKey,TValue>, like SortedDictionary<TKey,TValue>, uses a key to sort key-value pairs. Unlike SortedDictionary, however, items in a SortedList are stored as an ordered array of items. This means that insertions and deletions are linear - O(n) - because deleting or adding an item may involve shifting all items up or down in the list. Lookup time, however is O(log n) because the SortedList can use a binary search to find any item in the list by its key. So why would you ever want to do this? Well, the answer is that if you are going to load the SortedList up-front, the insertions will be slower, but because array indexing is faster than following object links, lookups are marginally faster than a SortedDictionary. Once again I'd use this in situations where you want fast lookups and want to maintain the collection in order by the key, and where insertions and deletions are rare. The Non-Associative Containers The other container classes are non-associative. They don't use keys to manipulate the collection but rely on the object itself being stored or some other means (such as index) to manipulate the collection. The List<T> is a basic contiguous storage container. Some people may call this a vector or dynamic array. Essentially it is an array of items that grow once its current capacity is exceeded. Because the items are stored contiguously as an array, you can access items in the List<T> by index very quickly. However inserting and removing in the beginning or middle of the List<T> are very costly because you must shift all the items up or down as you delete or insert respectively. However, adding and removing at the end of a List<T> is an amortized constant operation - O(1). Typically List<T> is the standard go-to collection when you don't have any other constraints, and typically we favor a List<T> even over arrays unless we are sure the size will remain absolutely fixed. The LinkedList<T> is a basic implementation of a doubly-linked list. This means that you can add or remove items in the middle of a linked list very quickly (because there's no items to move up or down in contiguous memory), but you also lose the ability to index items by position quickly. Most of the time we tend to favor List<T> over LinkedList<T> unless you are doing a lot of adding and removing from the collection, in which case a LinkedList<T> may make more sense. The HashSet<T> is an unordered collection of unique items. This means that the collection cannot have duplicates and no order is maintained. Logically, this is very similar to having a Dictionary<TKey,TValue> where the TKey and TValue both refer to the same object. This collection is very useful for maintaining a collection of items you wish to check membership against. For example, if you receive an order for a given vendor code, you may want to check to make sure the vendor code belongs to the set of vendor codes you handle. In these cases a HashSet<T> is useful for super-quick lookups where order is not important. Once again, like in Dictionary, the type T should have a valid implementation of GetHashCode() and Equals(), or you should provide an appropriate IEqualityComparer<T> to the HashSet<T> on construction. The SortedSet<T> is to HashSet<T> what the SortedDictionary<TKey,TValue> is to Dictionary<TKey,TValue>. That is, the SortedSet<T> is a binary tree where the key and value are the same object. This once again means that adding/removing/lookups are logarithmic - O(log n) - but you gain the ability to iterate over the items in order. For this collection to be effective, type T must implement IComparable<T> or you need to supply an external IComparer<T>. Finally, the Stack<T> and Queue<T> are two very specific collections that allow you to handle a sequential collection of objects in very specific ways. The Stack<T> is a last-in-first-out (LIFO) container where items are added and removed from the top of the stack. Typically this is useful in situations where you want to stack actions and then be able to undo those actions in reverse order as needed. The Queue<T> on the other hand is a first-in-first-out container which adds items at the end of the queue and removes items from the front. This is useful for situations where you need to process items in the order in which they came, such as a print spooler or waiting lines. So that's the basic collections. Let's summarize what we've learned in a quick reference table.  Collection Ordered? Contiguous Storage? Direct Access? Lookup Efficiency Manipulate Efficiency Notes Dictionary No Yes Via Key Key: O(1) O(1) Best for high performance lookups. SortedDictionary Yes No Via Key Key: O(log n) O(log n) Compromise of Dictionary speed and ordering, uses binary search tree. SortedList Yes Yes Via Key Key: O(log n) O(n) Very similar to SortedDictionary, except tree is implemented in an array, so has faster lookup on preloaded data, but slower loads. List No Yes Via Index Index: O(1) Value: O(n) O(n) Best for smaller lists where direct access required and no ordering. LinkedList No No No Value: O(n) O(1) Best for lists where inserting/deleting in middle is common and no direct access required. HashSet No Yes Via Key Key: O(1) O(1) Unique unordered collection, like a Dictionary except key and value are same object. SortedSet Yes No Via Key Key: O(log n) O(log n) Unique ordered collection, like SortedDictionary except key and value are same object. Stack No Yes Only Top Top: O(1) O(1)* Essentially same as List<T> except only process as LIFO Queue No Yes Only Front Front: O(1) O(1) Essentially same as List<T> except only process as FIFO   The Original Collections: System.Collections namespace The original collection classes are largely considered deprecated by developers and by Microsoft itself. In fact they indicate that for the most part you should always favor the generic or concurrent collections, and only use the original collections when you are dealing with legacy .NET code. Because these collections are out of vogue, let's just briefly mention the original collection and their generic equivalents: ArrayList A dynamic, contiguous collection of objects. Favor the generic collection List<T> instead. Hashtable Associative, unordered collection of key-value pairs of objects. Favor the generic collection Dictionary<TKey,TValue> instead. Queue First-in-first-out (FIFO) collection of objects. Favor the generic collection Queue<T> instead. SortedList Associative, ordered collection of key-value pairs of objects. Favor the generic collection SortedList<T> instead. Stack Last-in-first-out (LIFO) collection of objects. Favor the generic collection Stack<T> instead. In general, the older collections are non-type-safe and in some cases less performant than their generic counterparts. Once again, the only reason you should fall back on these older collections is for backward compatibility with legacy code and libraries only. The Concurrent Collections: System.Collections.Concurrent namespace The concurrent collections are new as of .NET 4.0 and are included in the System.Collections.Concurrent namespace. These collections are optimized for use in situations where multi-threaded read and write access of a collection is desired. The concurrent queue, stack, and dictionary work much as you'd expect. The bag and blocking collection are more unique. Below is the summary of each with a link to a blog post I did on each of them. ConcurrentQueue Thread-safe version of a queue (FIFO). For more information see: C#/.NET Little Wonders: The ConcurrentStack and ConcurrentQueue ConcurrentStack Thread-safe version of a stack (LIFO). For more information see: C#/.NET Little Wonders: The ConcurrentStack and ConcurrentQueue ConcurrentBag Thread-safe unordered collection of objects. Optimized for situations where a thread may be bother reader and writer. For more information see: C#/.NET Little Wonders: The ConcurrentBag and BlockingCollection ConcurrentDictionary Thread-safe version of a dictionary. Optimized for multiple readers (allows multiple readers under same lock). For more information see C#/.NET Little Wonders: The ConcurrentDictionary BlockingCollection Wrapper collection that implement producers & consumers paradigm. Readers can block until items are available to read. Writers can block until space is available to write (if bounded). For more information see C#/.NET Little Wonders: The ConcurrentBag and BlockingCollection Summary The .NET BCL has lots of collections built in to help you store and manipulate collections of data. Understanding how these collections work and knowing in which situations each container is best is one of the key skills necessary to build more performant code. Choosing the wrong collection for the job can make your code much slower or even harder to maintain if you choose one that doesn’t perform as well or otherwise doesn’t exactly fit the situation. Remember to avoid the original collections and stick with the generic collections.  If you need concurrent access, you can use the generic collections if the data is read-only, or consider the concurrent collections for mixed-access if you are running on .NET 4.0 or higher.   Tweet Technorati Tags: C#,.NET,Collecitons,Generic,Concurrent,Dictionary,List,Stack,Queue,SortedList,SortedDictionary,HashSet,SortedSet

    Read the article

  • Implementing Linked Lists in C#

    - by nijhawan.saurabh
    Why? The question is why you need Linked Lists and why it is the foundation of any Abstract Data Structure. Take any of the Data Structures - Stacks, Queues, Heaps, Trees; there are two ways to go about implementing them - Using Arrays Using Linked Lists Now you use Arrays when you know about the size of the Nodes in the list at Compile time and Linked Lists are helpful where you are free to add as many Nodes to the List as required at Runtime.   How? Now, let's see how we go about implementing a Simple Linked List in C#. Note: We'd be dealing with singly linked list for time being, there's also another version of linked lists - the Doubly Linked List which maintains two pointers (NEXT and BEFORE).   Class Diagram Let's see the Class Diagram first:     Code     1 // -----------------------------------------------------------------------     2 // <copyright file="Node.cs" company="">     3 // TODO: Update copyright text.     4 // </copyright>     5 // -----------------------------------------------------------------------     6      7 namespace CSharpAlgorithmsAndDS     8 {     9     using System;    10     using System.Collections.Generic;    11     using System.Linq;    12     using System.Text;    13     14     /// <summary>    15     /// TODO: Update summary.    16     /// </summary>    17     public class Node    18     {    19         public Object data { get; set; }    20     21         public Node Next { get; set; }    22     }    23 }    24         1 // -----------------------------------------------------------------------     2 // <copyright file="LinkedList.cs" company="">     3 // TODO: Update copyright text.     4 // </copyright>     5 // -----------------------------------------------------------------------     6      7 namespace CSharpAlgorithmsAndDS     8 {     9     using System;    10     using System.Collections.Generic;    11     using System.Linq;    12     using System.Text;    13     14     /// <summary>    15     /// TODO: Update summary.    16     /// </summary>    17     public class LinkedList    18     {    19         private Node Head;    20     21         public void AddNode(Node n)    22         {    23             n.Next = this.Head;    24             this.Head = n;    25     26         }    27     28         public void printNodes()    29         {    30     31             while (Head!=null)    32             {    33                 Console.WriteLine(Head.data);    34                 Head = Head.Next;    35     36             }    37     38         }    39     }    40 }    41          1 using System;     2 using System.Collections.Generic;     3 using System.Linq;     4 using System.Text;     5      6 namespace CSharpAlgorithmsAndDS     7 {     8     class Program     9     {    10         static void Main(string[] args)    11         {    12             LinkedList ll = new LinkedList();    13             Node A = new Node();    14             A.data = "A";    15     16             Node B = new Node();    17             B.data = "B";    18     19             Node C = new Node();    20             C.data = "C";    21             ll.AddNode(A);    22             ll.AddNode(B);    23             ll.AddNode(C);    24     25             ll.printNodes();    26         }    27     }    28 }    29        Final Words This is just a start, I will add more posts on Linked List covering more operations like Delete etc. and will also explore Doubly Linked List / Implementing Stacks/ Heaps/ Trees / Queues and what not using Linked Lists.   Normal 0 false false false EN-US X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin-top:0in; mso-para-margin-right:0in; mso-para-margin-bottom:10.0pt; mso-para-margin-left:0in; line-height:115%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi;}

    Read the article

  • JNI loses reference to native methods

    - by lhw
    As an example for later use in Android I wrote a simple callback interface. While doing so i ran into the following error or bug or whatever. In C the two commented lines are supposed to be executed resulting in calling the C callback onChange. But instead i get an UnsatisfiedLinkError. Calling the native Method directly in Java works just fine. Calling it directly from C as presented here in the example also produces the UnsatisfiedLinkError. I'm open for any advice concerning this issue or work arounds and so on. The Java Part: import java.util.LinkedList; import java.util.Random; interface Listener { public void onChange(float f); } class Provider { LinkedList<Listener> all; public Provider() { all = new LinkedList<Listener>(); } public void registerChange(Listener lst) { all.add(lst); } public void sendMsg() { Random rnd = new Random(); for(Listener l : all) { try { l.onChange(rnd.nextFloat()); } catch(Exception e) { System.out.println(e); } } } } class Inheritance implements Listener { static public void main(String[] args) { System.load(System.getProperty("user.dir") + "/libinheritance.so"); } public native void onChange(float f); } The C Part: #include "inheritance.h" jint JNI_OnLoad(JavaVM *jvm, void *reserved) { JNIEnv *env; (*jvm)->GetEnv(jvm, (void**)&env, JNI_VERSION_1_4); inheritance = (*env)->FindClass(env, "Inheritance"); o_inheritance = (*env)->NewObject(env, inheritance, (*env)->GetMethodID(env, inheritance, "<init>", "()V")); provider = (*env)->FindClass(env, "Provider"); o_provider = (*env)->NewObject(env, provider, (*env)->GetMethodID(env, provider, "<init>", "()V")); (*env)->CallVoidMethod(env, o_inheritance, (*env)->GetMethodID(env, inheritance, "onChange", "(F)V"), 1.0); //(*env)->CallVoidMethod(env, o_provider, (*env)->GetMethodID(env, provider, "registerChange", "(LListener;)V"), o_inheritance); //(*env)->CallVoidMethod(env, o_provider, (*env)->GetMethodID(env, provider, "sendMsg", "()V")); (*env)->DeleteLocalRef(env, o_inheritance); (*env)->DeleteLocalRef(env, o_provider); return JNI_VERSION_1_4; } JNIEXPORT void JNICALL Java_Inheritance_onChange(JNIEnv *env, jobject self, jfloat f) { printf("[C] %f\n", f); } The header file: #include <jni.h> /* Header for class Inheritance */ #ifndef _Included_Inheritance #define _Included_Inheritance #ifdef __cplusplus extern "C" { #endif jclass inheritance, provider; jobject o_inheritance, o_provider; /* * Class: Inheritance * Method: onChange * Signature: (F)V */ JNIEXPORT void JNICALL Java_Inheritance_onChange(JNIEnv *, jobject, jfloat); jint JNI_OnLoad(JavaVM *, void *); #ifdef __cplusplus } #endif #endif Compilation: gcc -c -fPIC -I /usr/lib/jvm/java-6-openjdk/include -I /usr/lib/jvm/java-6-openjdk/include/linux/inheritance.c inheritance.h gcc -g -o -shared libinheritance.so -shared -Wl,-soname,libinheritance.so -lc inheritance.o

    Read the article

  • Special kind of queue

    - by devoured elysium
    I am looking for something like a Queue that would allow me to put elements at the end of the queue and pop them out in the beggining, like a regular Queue does. The difference would be that I also need to compact the Queue from time to time. This is, let's assume I have the following items on my Queue (each character, including the dot, is an item in the Queue): e d . c . b . a (this Queue has 8 items) Then, I'd need for example to remove the last dot, so to get: e d . c . b a Is there anything like that in the Java Collection classes? I need to use this for a program I am doing where I can't use anything but Java's classes. I am not allowed to design one for myself. Currently I'm just using a LinkedList, but I thought maybe this would be more like a Queue than a LinkedList. Thanks

    Read the article

  • Java - Syntax Question: What is <? super T>

    - by aloh
    I'm having trouble understanding the following syntax: public class SortedList< T extends Comparable< ? super T> > extends LinkedList< T > I see that class SortedList extends LinkedList. I just don't know what T extends Comparable< ? super T> means. My understanding of it so far is that type T must be a type that implements Comparable...but what is "< ? super T "?

    Read the article

  • Thread help with Android game

    - by Ciph3rzer0
    I need some help dealing with three Threads in Android One thread is the main thread, the other is the GLThread, and the other is a WorkerThread I created to update the game state. The problem I have is they all need to access the same LinkedList of game objects. Both the GLThread and my WorkerThread only read from the LinkedList, so no problem there, but occasionally I have the main thread adding in another game object to the list. How can I manage this? I tried using synchronized in front of the functions involved but it really slows down the application. For some reason, just catching the errors and not rendering or updating the game state that frame, causes it to start lagging permanently. Anyone have any great ideas?

    Read the article

  • How to using String.split in this case?

    - by hoang nguyen
    I want to write a fuction like that: - Input: "1" -> return : "1" - Input: "12" -> return : ["1","2"] If I use the function split(): String.valueOf("12").split("") -> ["","1","2"] But, I only want to get the result: ["1","2"]. What the best way to do this? Infact, I can do that: private List<String> decomposeQuantity(final int quantity) { LinkedList<String> list = new LinkedList<String>(); int parsedQuantity = quantity; while (parsedQuantity > 0) { list.push(String.valueOf(parsedQuantity % 10)); parsedQuantity = parsedQuantity / 10; } return list; } But, I want to use split() for having an affective code

    Read the article

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