Search Results

Search found 30 results on 2 pages for 'arraycopy'.

Page 1/2 | 1 2  | Next Page >

  • Why is System.arraycopy native in Java?

    - by James B
    I was surprised to see in the Java source that System.arraycopy is a native method. Of course the reason is because it's faster. But what native tricks is the code able to employ that make it faster? Why not just loop over the original array and copy each pointer to the new array - surely this isn't that slow and cumbersome? Thanks, -James

    Read the article

  • "java.lang.ArrayIndexOutOfBoundsException" with System.arraycopy()

    - by Noona
    These few lines of code are giving me a "java.lang.ArrayIndexOutOfBoundsException" exception, could someone please take a look and point out why (the exception is caused in the second arraycopy() call): byte [] newContentBytes = EntityUtils.toByteArray((serverResponse.getEntity())); newContent = new String(newContentBytes); System.out.println( newContent); byte [] headerBytes = headers.getBytes(); byte[] res = new byte[newContentBytes.length + headerBytes.length]; //headerBytes. System.arraycopy(headerBytes, 0, res, 0, headerBytes.length); System.out.println( "length: " + newContentBytes.length); System.arraycopy(newContentBytes, 0, res, newContentBytes.length , newContentBytes.length); The problem is in allocating res size, for example if I write new byte[newContentBytes.length + headerBytes.length+ 2000] instead the exception doesn't occur, so what should the accurate size be?

    Read the article

  • JAVA image transfer problem

    - by user579098
    Hi, I have a school assignment, to send a jpg image,split it into groups of 100 bytes, corrupt it, use a CRC check to locate the errors and re-transmit until it eventually is built back into its original form. It's practically ready, however when I check out the new images, they appear with errors.. I would really appreciate if someone could look at my code below and maybe locate this logical mistake as I can't understand what the problem is because everything looks ok :S For the file with all the data needed including photos and error patterns one could download it from this link:http://rapidshare.com/#!download|932tl2|443122762|Data.zip|739 Thanks in advance, Stefan p.s dont forget to change the paths in the code for the image and error files package networks; import java.io.*; // for file reader import java.util.zip.CRC32; // CRC32 IEEE (Ethernet) public class Main { /** * Reads a whole file into an array of bytes. * @param file The file in question. * @return Array of bytes containing file data. * @throws IOException Message contains why it failed. */ public static byte[] readFileArray(File file) throws IOException { InputStream is = new FileInputStream(file); byte[] data=new byte[(int)file.length()]; is.read(data); is.close(); return data; } /** * Writes (or overwrites if exists) a file with data from an array of bytes. * @param file The file in question. * @param data Array of bytes containing the new file data. * @throws IOException Message contains why it failed. */ public static void writeFileArray(File file, byte[] data) throws IOException { OutputStream os = new FileOutputStream(file,false); os.write(data); os.close(); } /** * Converts a long value to an array of bytes. * @param data The target variable. * @return Byte array conversion of data. * @see http://www.daniweb.com/code/snippet216874.html */ public static byte[] toByta(long data) { return new byte[] { (byte)((data >> 56) & 0xff), (byte)((data >> 48) & 0xff), (byte)((data >> 40) & 0xff), (byte)((data >> 32) & 0xff), (byte)((data >> 24) & 0xff), (byte)((data >> 16) & 0xff), (byte)((data >> 8) & 0xff), (byte)((data >> 0) & 0xff), }; } /** * Converts a an array of bytes to long value. * @param data The target variable. * @return Long value conversion of data. * @see http://www.daniweb.com/code/snippet216874.html */ public static long toLong(byte[] data) { if (data == null || data.length != 8) return 0x0; return (long)( // (Below) convert to longs before shift because digits // are lost with ints beyond the 32-bit limit (long)(0xff & data[0]) << 56 | (long)(0xff & data[1]) << 48 | (long)(0xff & data[2]) << 40 | (long)(0xff & data[3]) << 32 | (long)(0xff & data[4]) << 24 | (long)(0xff & data[5]) << 16 | (long)(0xff & data[6]) << 8 | (long)(0xff & data[7]) << 0 ); } public static byte[] nextNoise(){ byte[] result=new byte[100]; // copy a frame's worth of data (or remaining data if it is less than frame length) int read=Math.min(err_data.length-err_pstn, 100); System.arraycopy(err_data, err_pstn, result, 0, read); // if read data is less than frame length, reset position and add remaining data if(read<100){ err_pstn=100-read; System.arraycopy(err_data, 0, result, read, err_pstn); }else // otherwise, increase position err_pstn+=100; // return noise segment return result; } /** * Given some original data, it is purposefully corrupted according to a * second data array (which is read from a file). In pseudocode: * corrupt = original xor corruptor * @param data The original data. * @return The new (corrupted) data. */ public static byte[] corruptData(byte[] data){ // get the next noise sequence byte[] noise = nextNoise(); // finally, xor data with noise and return result for(int i=0; i<100; i++)data[i]^=noise[i]; return data; } /** * Given an array of data, a packet is created. In pseudocode: * frame = corrupt(data) + crc(data) * @param data The original frame data. * @return The resulting frame data. */ public static byte[] buildFrame(byte[] data){ // pack = [data]+crc32([data]) byte[] hash = new byte[8]; // calculate crc32 of data and copy it to byte array CRC32 crc = new CRC32(); crc.update(data); hash=toByta(crc.getValue()); // create a byte array holding the final packet byte[] pack = new byte[data.length+hash.length]; // create the corrupted data byte[] crpt = new byte[data.length]; crpt = corruptData(data); // copy corrupted data into pack System.arraycopy(crpt, 0, pack, 0, crpt.length); // copy hash into pack System.arraycopy(hash, 0, pack, data.length, hash.length); // return pack return pack; } /** * Verifies frame contents. * @param frame The frame data (data+crc32). * @return True if frame is valid, false otherwise. */ public static boolean verifyFrame(byte[] frame){ // allocate hash and data variables byte[] hash=new byte[8]; byte[] data=new byte[frame.length-hash.length]; // read frame into hash and data variables System.arraycopy(frame, frame.length-hash.length, hash, 0, hash.length); System.arraycopy(frame, 0, data, 0, frame.length-hash.length); // get crc32 of data CRC32 crc = new CRC32(); crc.update(data); // compare crc32 of data with crc32 of frame return crc.getValue()==toLong(hash); } /** * Transfers a file through a channel in frames and reconstructs it into a new file. * @param jpg_file File name of target file to transfer. * @param err_file The channel noise file used to simulate corruption. * @param out_file The name of the newly-created file. * @throws IOException */ public static void transferFile(String jpg_file, String err_file, String out_file) throws IOException { // read file data into global variables jpg_data = readFileArray(new File(jpg_file)); err_data = readFileArray(new File(err_file)); err_pstn = 0; // variable that will hold the final (transfered) data byte[] out_data = new byte[jpg_data.length]; // holds the current frame data byte[] frame_orig = new byte[100]; byte[] frame_sent = new byte[100]; // send file in chunks (frames) of 100 bytes for(int i=0; i<Math.ceil(jpg_data.length/100); i++){ // copy jpg data into frame and init first-time switch System.arraycopy(jpg_data, i*100, frame_orig, 0, 100); boolean not_first=false; System.out.print("Packet #"+i+": "); // repeat getting same frame until frame crc matches with frame content do { if(not_first)System.out.print("F"); frame_sent=buildFrame(frame_orig); not_first=true; }while(!verifyFrame(frame_sent)); // usually, you'd constrain this by time to prevent infinite loops (in // case the channel is so wacked up it doesn't get a single packet right) // copy frame to image file System.out.println("S"); System.arraycopy(frame_sent, 0, out_data, i*100, 100); } System.out.println("\nDone."); writeFileArray(new File(out_file),out_data); } // global variables for file data and pointer public static byte[] jpg_data; public static byte[] err_data; public static int err_pstn=0; public static void main(String[] args) throws IOException { // list of jpg files String[] jpg_file={ "C:\\Users\\Stefan\\Desktop\\Data\\Images\\photo1.jpg", "C:\\Users\\Stefan\\Desktop\\Data\\Images\\photo2.jpg", "C:\\Users\\Stefan\\Desktop\\Data\\Images\\photo3.jpg", "C:\\Users\\Stefan\\Desktop\\Data\\Images\\photo4.jpg" }; // list of error patterns String[] err_file={ "C:\\Users\\Stefan\\Desktop\\Data\\Error Pattern\\Error Pattern 1.DAT", "C:\\Users\\Stefan\\Desktop\\Data\\Error Pattern\\Error Pattern 2.DAT", "C:\\Users\\Stefan\\Desktop\\Data\\Error Pattern\\Error Pattern 3.DAT", "C:\\Users\\Stefan\\Desktop\\Data\\Error Pattern\\Error Pattern 4.DAT" }; // loop through all jpg/channel combinations and run tests for(int x=0; x<jpg_file.length; x++){ for(int y=0; y<err_file.length; y++){ System.out.println("Transfering photo"+(x+1)+".jpg using Pattern "+(y+1)+"..."); transferFile(jpg_file[x],err_file[y],jpg_file[x].replace("photo","CH#"+y+"_photo")); } } } }

    Read the article

  • How to effectively copy an array in java ?

    - by Tony
    The toArray method in ArrayList , Bloch uses both System.arraycopy and Arrays.copyOf to copy an array . public <T> T[] toArray(T[] a) { if (a.length < size) // Make a new array of a's runtime type, but my contents: return (T[]) Arrays.copyOf(elementData, size, a.getClass()); System.arraycopy(elementData, 0, a, 0, size); if (a.length > size) a[size] = null; return a; } How to compare these two copy method , when to use which ? Thanks.

    Read the article

  • Java: How ArrayList memory management

    - by cka3o4nik
    In my Data Structures class we have studies the Java ArrayList class, and how it grows the underlying array when a user adds more elements. That is understood. However, I cannot figure out how exactly this class frees up memory when lots of elements are removed from the list. Looking at the source, there are three methods that remove elements: [code] public E remove(int index) { RangeCheck(index); modCount++; E oldValue = (E) elementData[index]; int numMoved = size - index - 1; if (numMoved 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // Let gc do its work return oldValue; } public boolean remove(Object o) { if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); return true; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); return true; } } return false; } private void fastRemove(int index) { modCount++; int numMoved = size - index - 1; if (numMoved 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // Let gc do its work } {/code] None of them reduce the datastore array. I even started questioning if memory free up ever happens, but empirical tests show that it does. So there must be some other way it is done, but where and how? I checked the parent classes as well with no success.

    Read the article

  • BouncyCastle GCM/CCM Exceprion in JAVA

    - by 4r1y4n
    can anyone give me an example for using GCM and/or CCM modes with AES in BouncyCastle? My code is this: SecretKeySpec key = new SecretKeySpec(keyBytes, "AES"); IvParameterSpec ivSpec = new IvParameterSpec(ivBytes); Cipher cipher = Cipher.getInstance("AES/AEAD/PKCS5Padding", "BC"); byte[] block = new byte[1048576]; int i; long st,et; cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec); BufferedInputStream bIn=new BufferedInputStream(new ProgressMonitorInputStream(null,"Encrypting ...",new FileInputStream("input"))); CipherInputStream cIn = new CipherInputStream(bIn, cipher); BufferedOutputStream bOut=new BufferedOutputStream(new FileOutputStream("output.enc")); int ch; while ((i = cIn.read(block)) != -1) { bOut.write(block, 0, i); } cIn.close(); bOut.close(); Thread.sleep(5000); cipher.init(Cipher.DECRYPT_MODE, key, ivSpec); BufferedInputStream fis=new BufferedInputStream(new ProgressMonitorInputStream(null,"Decrypting ...",new FileInputStream("output.enc"))); //FileInputStream fis=new FileInputStream("output.enc"); //FileOutputStream ro=new FileOutputStream("regen.plain"); BufferedOutputStream ro=new BufferedOutputStream(new FileOutputStream("regen.plain")); CipherInputStream dcIn = new CipherInputStream(fis, cipher); while ((i = dcIn.read(block)) != -1) { ro.write(block, 0, i); } dcIn.close(); ro.close(); but it throws this exception when decrypting in GCM mode (line 70 is bOut.write(block, 0, i);): Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at java.lang.System.arraycopy(Native Method) at org.bouncycastle.crypto.modes.CCMBlockCipher.processPacket(Unknown Source) at org.bouncycastle.crypto.modes.CCMBlockCipher.doFinal(Unknown Source) at org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher$AEADGenericBlockCipher.doFinal(Unknown Source) at org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(Unknown Source) at javax.crypto.Cipher.doFinal(DashoA13*..) at javax.crypto.CipherInputStream.a(DashoA13*..) at javax.crypto.CipherInputStream.read(DashoA13*..) at javax.crypto.CipherInputStream.read(DashoA13*..) at enctest.Main.main(Main.java:70) And this Exception when encrypting in CCM mode (line 70 is bOut.write(block, 0, i);): Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at java.lang.System.arraycopy(Native Method) at org.bouncycastle.crypto.modes.CCMBlockCipher.processPacket(Unknown Source) at org.bouncycastle.crypto.modes.CCMBlockCipher.doFinal(Unknown Source) at org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher$AEADGenericBlockCipher.doFinal(Unknown Source) at org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(Unknown Source) at javax.crypto.Cipher.doFinal(DashoA13*..) at javax.crypto.CipherInputStream.a(DashoA13*..) at javax.crypto.CipherInputStream.read(DashoA13*..) at javax.crypto.CipherInputStream.read(DashoA13*..) at enctest.Main.main(Main.java:70)

    Read the article

  • MiniMax not working properly(for checkers game)

    - by engineer
    I am creating a checkers game but My miniMax is not functioning properly,it is always switching between two positions for its move(index 20 and 17).Here is my code: public double MiniMax(int[] board, int depth, int turn, int red_best, int black_best) { int source; int dest; double MAX_SCORE=-INFINITY,newScore; int MAX_DEPTH=3; int[] newBoard=new int[32]; generateMoves(board,turn); System.arraycopy(board, 0, newBoard, 0, 32); if(depth==MAX_DEPTH) { return Evaluation(turn,board);} for(int z=0;z<possibleMoves.size();z+=2){ source=Integer.parseInt(possibleMoves.elementAt(z).toString()); System.out.println("SOURCE= "+source); dest=Integer.parseInt(possibleMoves.elementAt(z+1).toString());//(int[])possibleMoves.elementAt(z+1); System.out.println("DEST = "+dest); applyMove(newBoard,source,dest); newScore=MiniMax(newBoard,depth+1,opponent(turn),red_best, black_best); if(newScore>MAX_SCORE) {MAX_SCORE=newScore;maxSource=source; maxDest=dest;}//maxSource and maxDest will be used to perform the move. if (MAX_SCORE > black_best) { if (MAX_SCORE >= red_best) break; /* alpha_beta cutoff */ else black_best = (int) MAX_SCORE; //the_score } if (MAX_SCORE < red_best) { if (MAX_SCORE<= black_best) break; /* alpha_beta cutoff */ else red_best = (int) MAX_SCORE; //the_score } }//for ends return MAX_SCORE; } //end minimax I am unable to find out the logical mistake. Any idea what's going wrong?

    Read the article

  • Convert Java program to C

    - by imicrothinking
    I need a bit of guidance with writing a C program...a bit of quick background as to my level, I've programmed in Java previously, but this is my first time programming in C, and we've been tasked to translate a word count program from Java to C that consists of the following: Read a file from memory Count the words in the file For each occurrence of a unique word, keep a word counter variable Print out the top ten most frequent words and their corresponding occurrences Here's the source program in Java: package lab0; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; public class WordCount { private ArrayList<WordCountNode> outputlist = null; public WordCount(){ this.outputlist = new ArrayList<WordCountNode>(); } /** * Read the file into memory. * * @param filename name of the file. * @return content of the file. * @throws Exception if the file is too large or other file related exception. */ public char[] readFile(String filename) throws Exception{ char [] result = null; File file = new File(filename); long size = file.length(); if (size > Integer.MAX_VALUE){ throw new Exception("File is too large"); } result = new char[(int)size]; FileReader reader = new FileReader(file); int len, offset = 0, size2read = (int)size; while(size2read > 0){ len = reader.read(result, offset, size2read); if(len == -1) break; size2read -= len; offset += len; } return result; } /** * Make article word by word. * * @param article the content of file to be counted. * @return string contains only letters and "'". */ private enum SPLIT_STATE {IN_WORD, NOT_IN_WORD}; /** * Go through article, find all the words and add to output list * with their count. * * @param article the content of the file to be counted. * @return words in the file and their counts. */ public ArrayList<WordCountNode> countWords(char[] article){ SPLIT_STATE state = SPLIT_STATE.NOT_IN_WORD; if(null == article) return null; char curr_ltr; int curr_start = 0; for(int i = 0; i < article.length; i++){ curr_ltr = Character.toUpperCase( article[i]); if(state == SPLIT_STATE.IN_WORD){ article[i] = curr_ltr; if ((curr_ltr < 'A' || curr_ltr > 'Z') && curr_ltr != '\'') { article[i] = ' '; //printf("\nthe word is %s\n\n",curr_start); if(i - curr_start < 0){ System.out.println("i = " + i + " curr_start = " + curr_start); } addWord(new String(article, curr_start, i-curr_start)); state = SPLIT_STATE.NOT_IN_WORD; } }else{ if (curr_ltr >= 'A' && curr_ltr <= 'Z') { curr_start = i; article[i] = curr_ltr; state = SPLIT_STATE.IN_WORD; } } } return outputlist; } /** * Add the word to output list. */ public void addWord(String word){ int pos = dobsearch(word); if(pos >= outputlist.size()){ outputlist.add(new WordCountNode(1L, word)); }else{ WordCountNode tmp = outputlist.get(pos); if(tmp.getWord().compareTo(word) == 0){ tmp.setCount(tmp.getCount() + 1); }else{ outputlist.add(pos, new WordCountNode(1L, word)); } } } /** * Search the output list and return the position to put word. * @param word is the word to be put into output list. * @return position in the output list to insert the word. */ public int dobsearch(String word){ int cmp, high = outputlist.size(), low = -1, next; // Binary search the array to find the key while (high - low > 1) { next = (high + low) / 2; // all in upper case cmp = word.compareTo((outputlist.get(next)).getWord()); if (cmp == 0) return next; else if (cmp < 0) high = next; else low = next; } return high; } public static void main(String args[]){ // handle input if (args.length == 0){ System.out.println("USAGE: WordCount <filename> [Top # of results to display]\n"); System.exit(1); } String filename = args[0]; int dispnum; try{ dispnum = Integer.parseInt(args[1]); }catch(Exception e){ dispnum = 10; } long start_time = Calendar.getInstance().getTimeInMillis(); WordCount wordcount = new WordCount(); System.out.println("Wordcount: Running..."); // read file char[] input = null; try { input = wordcount.readFile(filename); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); System.exit(1); } // count all word ArrayList<WordCountNode> result = wordcount.countWords(input); long end_time = Calendar.getInstance().getTimeInMillis(); System.out.println("wordcount: completed " + (end_time - start_time)/1000000 + "." + (end_time - start_time)%1000000 + "(s)"); System.out.println("wordsort: running ..."); start_time = Calendar.getInstance().getTimeInMillis(); Collections.sort(result); end_time = Calendar.getInstance().getTimeInMillis(); System.out.println("wordsort: completed " + (end_time - start_time)/1000000 + "." + (end_time - start_time)%1000000 + "(s)"); Collections.reverse(result); System.out.println("\nresults (TOP "+ dispnum +" from "+ result.size() +"):\n" ); // print out result String str ; for (int i = 0; i < result.size() && i < dispnum; i++){ if(result.get(i).getWord().length() > 15) str = result.get(i).getWord().substring(0, 14); else str = result.get(i).getWord(); System.out.println(str + " - " + result.get(i).getCount()); } } public class WordCountNode implements Comparable{ private String word; private long count; public WordCountNode(long count, String word){ this.count = count; this.word = word; } public String getWord() { return word; } public void setWord(String word) { this.word = word; } public long getCount() { return count; } public void setCount(long count) { this.count = count; } public int compareTo(Object arg0) { // TODO Auto-generated method stub WordCountNode obj = (WordCountNode)arg0; if( count - obj.getCount() < 0) return -1; else if( count - obj.getCount() == 0) return 0; else return 1; } } } Here's my attempt (so far) in C: #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> // Read in a file FILE *readFile (char filename[]) { FILE *inputFile; inputFile = fopen (filename, "r"); if (inputFile == NULL) { printf ("File could not be opened.\n"); exit (EXIT_FAILURE); } return inputFile; } // Return number of words in an array int wordCount (FILE *filePointer, char filename[]) {//, char *words[]) { // count words int count = 0; char temp; while ((temp = getc(filePointer)) != EOF) { //printf ("%c", temp); if ((temp == ' ' || temp == '\n') && (temp != '\'')) count++; } count += 1; // counting method uses space AFTER last character in word - the last space // of the last character isn't counted - off by one error // close file fclose (filePointer); return count; } // Print out the frequencies of the 10 most frequent words in the console int main (int argc, char *argv[]) { /* Step 1: Read in file and check for errors */ FILE *filePointer; filePointer = readFile (argv[1]); /* Step 2: Do a word count to prep for array size */ int count = wordCount (filePointer, argv[1]); printf ("Number of words is: %i\n", count); /* Step 3: Create a 2D array to store words in the file */ // open file to reset marker to beginning of file filePointer = fopen (argv[1], "r"); // store words in character array (each element in array = consecutive word) char allWords[count][100]; // 100 is an arbitrary size - max length of word int i,j; char temp; for (i = 0; i < count; i++) { for (j = 0; j < 100; j++) { // labels are used with goto statements, not loops in C temp = getc(filePointer); if ((temp == ' ' || temp == '\n' || temp == EOF) && (temp != '\'') ) { allWords[i][j] = '\0'; break; } else { allWords[i][j] = temp; } printf ("%c", allWords[i][j]); } printf ("\n"); } // close file fclose (filePointer); /* Step 4: Use a simple selection sort algorithm to sort 2D char array */ // PStep 1: Compare two char arrays, and if // (a) c1 > c2, return 2 // (b) c1 == c2, return 1 // (c) c1 < c2, return 0 qsort(allWords, count, sizeof(char[][]), pstrcmp); /* int k = 0, l = 0, m = 0; char currentMax, comparedElement; int max; // the largest element in the current 2D array int elementToSort = 0; // elementToSort determines the element to swap with starting from the left // Outer a iterates through number of swaps needed for (k = 0; k < count - 1; k++) { // times of swaps max = k; // max element set to k // Inner b iterates through successive elements to fish out the largest element for (m = k + 1; m < count - k; m++) { currentMax = allWords[k][l]; comparedElement = allWords[m][l]; // Inner c iterates through successive chars to set the max vars to the largest for (l = 0; (currentMax != '\0' || comparedElement != '\0'); l++) { if (currentMax > comparedElement) break; else if (currentMax < comparedElement) { max = m; currentMax = allWords[m][l]; break; } else if (currentMax == comparedElement) continue; } } // After max (count and string) is determined, perform swap with temp variable char swapTemp[1][20]; int y = 0; do { swapTemp[0][y] = allWords[elementToSort][y]; allWords[elementToSort][y] = allWords[max][y]; allWords[max][y] = swapTemp[0][y]; } while (swapTemp[0][y++] != '\0'); elementToSort++; } */ int a, b; for (a = 0; a < count; a++) { for (b = 0; (temp = allWords[a][b]) != '\0'; b++) { printf ("%c", temp); } printf ("\n"); } // Copy rows to different array and print results /* char arrayCopy [count][20]; int ac, ad; char tempa; for (ac = 0; ac < count; ac++) { for (ad = 0; (tempa = allWords[ac][ad]) != '\0'; ad++) { arrayCopy[ac][ad] = tempa; printf("%c", arrayCopy[ac][ad]); } printf("\n"); } */ /* Step 5: Create two additional arrays: (a) One in which each element contains unique words from char array (b) One which holds the count for the corresponding word in the other array */ /* Step 6: Sort the count array in decreasing order, and print the corresponding array element as well as word count in the console */ return 0; } // Perform housekeeping tasks like freeing up memory and closing file I'm really stuck on the selection sort algorithm. I'm currently using 2D arrays to represent strings, and that worked out fine, but when it came to sorting, using three level nested loops didn't seem to work, I tried to use qsort instead, but I don't fully understand that function as well. Constructive feedback and criticism greatly welcome (...and needed)!

    Read the article

  • Java native methods issues with SUN JVM (jdk1.5.0_14) and multi-core CPU’s

    - by Mattias Arnersten
    We are hosting an application on SUN JVM that handles a lot of XML parsing using Jaxb. The application is parsing the XML fine using JRockit 5 but when using the SUN JVM the JVM spends a majority of it’s time on native methods such as java-lang.System.arraycopy, java.lang.String.intern and java.lang.ClassLoader.getPackage. The CPU load is approx. 60% higher when using SUN JVM compared with JRockit. Even stranger is that when we only run the application server using one core (in WMWare) the problem disappears. Has anyone experienced the same behavior? Mattias Arnersten

    Read the article

  • Java - Thread safety of ArrayList constructors

    - by andy boot
    I am looking at this piece of code. This constructor delegates to the native method "System.arraycopy" Is it Thread safe? And by that I mean can it ever throw a ConcurrentModificationException? public Collection<Object> getConnections(Collection<Object> someCollection) { return new ArrayList<Object>(someCollection); } Does it make any difference if the collection being copied is ThreadSafe eg a CopyOnWriteArrayList? public Collection<Object> getConnections(CopyOnWriteArrayList<Object> someCollection) { return new ArrayList<Object>(someCollection); }

    Read the article

  • Multiple (variant) arguments overloading in Java: What's the purpose?

    - by fortran
    Browsing google's guava collect library code, I've found the following: // Casting to any type is safe because the list will never hold any elements. @SuppressWarnings("unchecked") public static <E> ImmutableList<E> of() { return (ImmutableList<E>) EmptyImmutableList.INSTANCE; } public static <E> ImmutableList<E> of(E element) { return new SingletonImmutableList<E>(element); } public static <E> ImmutableList<E> of(E e1, E e2) { return new RegularImmutableList<E>( ImmutableList.<E>nullCheckedList(e1, e2)); } public static <E> ImmutableList<E> of(E e1, E e2, E e3) { return new RegularImmutableList<E>( ImmutableList.<E>nullCheckedList(e1, e2, e3)); } public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4) { return new RegularImmutableList<E>( ImmutableList.<E>nullCheckedList(e1, e2, e3, e4)); } public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5) { return new RegularImmutableList<E>( ImmutableList.<E>nullCheckedList(e1, e2, e3, e4, e5)); } public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6) { return new RegularImmutableList<E>( ImmutableList.<E>nullCheckedList(e1, e2, e3, e4, e5, e6)); } public static <E> ImmutableList<E> of( E e1, E e2, E e3, E e4, E e5, E e6, E e7) { return new RegularImmutableList<E>( ImmutableList.<E>nullCheckedList(e1, e2, e3, e4, e5, e6, e7)); } public static <E> ImmutableList<E> of( E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8) { return new RegularImmutableList<E>( ImmutableList.<E>nullCheckedList(e1, e2, e3, e4, e5, e6, e7, e8)); } public static <E> ImmutableList<E> of( E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9) { return new RegularImmutableList<E>( ImmutableList.<E>nullCheckedList(e1, e2, e3, e4, e5, e6, e7, e8, e9)); } public static <E> ImmutableList<E> of( E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10) { return new RegularImmutableList<E>(ImmutableList.<E>nullCheckedList( e1, e2, e3, e4, e5, e6, e7, e8, e9, e10)); } public static <E> ImmutableList<E> of( E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10, E e11) { return new RegularImmutableList<E>(ImmutableList.<E>nullCheckedList( e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11)); } public static <E> ImmutableList<E> of( E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10, E e11, E e12, E... others) { final int paramCount = 12; Object[] array = new Object[paramCount + others.length]; arrayCopy(array, 0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12); arrayCopy(array, paramCount, others); return new RegularImmutableList<E>(ImmutableList.<E>nullCheckedList(array)); } And although it seems reasonable to have overloads for empty and single arguments (as they are going to use special instances), I cannot see the reason behind having all the others, when just the last one (with two fixed arguments plus the variable argument instead the dozen) seems to be enough. As I'm writing, one explanation that pops into my head is that the API pre-dates Java 1.5; and although the signatures would be source-level compatible, the binary interface would differ. Isn't it?

    Read the article

  • How to copy a subset from an array of strings to an array of ints using Groovy?

    - by Cuga
    I have a String array in a Groovy class (args to a main method): String[] args I'd like to convert the 3rd to the last element into a new array of ints. Is there an easier way to do this in Groovy other than: final int numInts = args.length - 2 final int [] intArray = new int[numInts] for (int i = 2; i < args.length; i++) { intArray[i-2]=Integer.parseInt(args[i]) } I wanted to do: final int numInts = args.length - 2 final int [] intArray = new int[numInts] System.arraycopy(args, 2, intArray, 0, numInts) But it throws a class cast exception. Thanks!

    Read the article

  • Questions related to writing your own file downloader using multiple threads java

    - by Shekhar
    Hello In my current company, i am doing a PoC on how we can write a file downloader utility. We have to use socket programming(TCP/IP) for downloading the files. One of the requirements of the client is that a file(which will be large in size) should be transfered in chunks for example if we have a file of 5Mb size then we can have 5 threads which transfer 1 Mb each. I have written a small application which downloads a file. You can download the eclipe project from http://www.fileflyer.com/view/QM1JSC0 A brief explanation of my classes FileSender.java This class provides the bytes of file. It has a method called sendBytesOfFile(long start,long end, long sequenceNo) which gives the number of bytes. import java.io.File; import java.io.IOException; import java.util.zip.CRC32; import org.apache.commons.io.FileUtils; public class FileSender { private static final String FILE_NAME = "C:\\shared\\test.pdf"; public ByteArrayWrapper sendBytesOfFile(long start,long end, long sequenceNo){ try { File file = new File(FILE_NAME); byte[] fileBytes = FileUtils.readFileToByteArray(file); System.out.println("Size of file is " +fileBytes.length); System.out.println(); System.out.println("Start "+start +" end "+end); byte[] bytes = getByteArray(fileBytes, start, end); ByteArrayWrapper wrapper = new ByteArrayWrapper(bytes, sequenceNo); return wrapper; } catch (IOException e) { throw new RuntimeException(e); } } private byte[] getByteArray(byte[] bytes, long start, long end){ long arrayLength = end-start; System.out.println("Start : "+start +" end : "+end + " Arraylength : "+arrayLength +" length of source array : "+bytes.length); byte[] arr = new byte[(int)arrayLength]; for(int i = (int)start, j =0; i < end;i++,j++){ arr[j] = bytes[i]; } return arr; } public static long fileSize(){ File file = new File(FILE_NAME); return file.length(); } } Second Class is FileReceiver.java - This class receives the file. Small Explanation what this file does This class finds the size of the file to be fetched from Sender Depending upon the size of the file it finds the start and end position till the bytes needs to be read. It starts n number of threads giving each thread start,end, sequence number and a list which all the threads share. Each thread reads the number of bytes and creates a ByteArrayWrapper. ByteArrayWrapper objects are added to the list Then i have while loop which basically make sure that all threads have done their work finally it sorts the list based on the sequence number. then the bytes are joined, and a complete byte array is formed which is converted to a file. Code of File Receiver package com.filedownloader; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.zip.CRC32; import org.apache.commons.io.FileUtils; public class FileReceiver { public static void main(String[] args) { FileReceiver receiver = new FileReceiver(); receiver.receiveFile(); } public void receiveFile(){ long startTime = System.currentTimeMillis(); long numberOfThreads = 10; long filesize = FileSender.fileSize(); System.out.println("File size received "+filesize); long start = filesize/numberOfThreads; List<ByteArrayWrapper> list = new ArrayList<ByteArrayWrapper>(); for(long threadCount =0; threadCount<numberOfThreads ;threadCount++){ FileDownloaderTask task = new FileDownloaderTask(threadCount*start,(threadCount+1)*start,threadCount,list); new Thread(task).start(); } while(list.size() != numberOfThreads){ // this is done so that all the threads should complete their work before processing further. //System.out.println("Waiting for threads to complete. List size "+list.size()); } if(list.size() == numberOfThreads){ System.out.println("All bytes received "+list); Collections.sort(list, new Comparator<ByteArrayWrapper>() { @Override public int compare(ByteArrayWrapper o1, ByteArrayWrapper o2) { long sequence1 = o1.getSequence(); long sequence2 = o2.getSequence(); if(sequence1 < sequence2){ return -1; }else if(sequence1 > sequence2){ return 1; } else{ return 0; } } }); byte[] totalBytes = list.get(0).getBytes(); byte[] firstArr = null; byte[] secondArr = null; for(int i = 1;i<list.size();i++){ firstArr = totalBytes; secondArr = list.get(i).getBytes(); totalBytes = concat(firstArr, secondArr); } System.out.println(totalBytes.length); convertToFile(totalBytes,"c:\\tmp\\test.pdf"); long endTime = System.currentTimeMillis(); System.out.println("Total time taken with "+numberOfThreads +" threads is "+(endTime-startTime)+" ms" ); } } private byte[] concat(byte[] A, byte[] B) { byte[] C= new byte[A.length+B.length]; System.arraycopy(A, 0, C, 0, A.length); System.arraycopy(B, 0, C, A.length, B.length); return C; } private void convertToFile(byte[] totalBytes,String name) { try { FileUtils.writeByteArrayToFile(new File(name), totalBytes); } catch (IOException e) { throw new RuntimeException(e); } } } Code of ByteArrayWrapper package com.filedownloader; import java.io.Serializable; public class ByteArrayWrapper implements Serializable{ private static final long serialVersionUID = 3499562855188457886L; private byte[] bytes; private long sequence; public ByteArrayWrapper(byte[] bytes, long sequenceNo) { this.bytes = bytes; this.sequence = sequenceNo; } public byte[] getBytes() { return bytes; } public long getSequence() { return sequence; } } Code of FileDownloaderTask import java.util.List; public class FileDownloaderTask implements Runnable { private List<ByteArrayWrapper> list; private long start; private long end; private long sequenceNo; public FileDownloaderTask(long start,long end,long sequenceNo,List<ByteArrayWrapper> list) { this.list = list; this.start = start; this.end = end; this.sequenceNo = sequenceNo; } @Override public void run() { ByteArrayWrapper wrapper = new FileSender().sendBytesOfFile(start, end, sequenceNo); list.add(wrapper); } } Questions related to this code 1) Does file downloading becomes fast when multiple threads is used? In this code i am not able to see the benefit. 2) How should i decide how many threads should i create ? 3) Are their any opensource libraries which does that 4) The file which file receiver receives is valid and not corrupted but checksum (i used FileUtils of common-io) does not match. Whats the problem? 5) This code gives out of memory when used with large file(above 100 Mb) i.e. because byte array which is created. How can i avoid? I know this is a very bad code but i have to write this in one day -:). Please suggest any other good way to do this? Thanks Shekhar

    Read the article

  • Implementing union of Set using basic java array

    - by lupindeterd
    Note: This is an assignment. Hi, Continuing with my Set implementation using Java basic array, I'm now struggling with the 3 to last function namely the union. import java.io.*; class Set { private int numberOfElements = 0; private String[] setElements = new String[5]; private int maxNumberOfElements = 5; // constructor for our Set class public Set(int numberOfE, int setE, int maxNumberOfE) { int numberOfElements = numberOfE; String[] setElements = new String[setE]; int maxNumberOfElements = maxNumberOfE; } // Helper method to shorten/remove element of array since we're using basic array instead of ArrayList or HashSet from collection interface :( static String[] removeAt(int k, String[] arr) { final int L = arr.length; String[] ret = new String[L - 1]; System.arraycopy(arr, 0, ret, 0, k); System.arraycopy(arr, k + 1, ret, k, L - k - 1); return ret; } int findElement(String element) { int retval = 0; for ( int i = 0; i < setElements.length; i++) { if ( setElements[i] != null && setElements[i].equals(element) ) { return retval = i; } retval = -1; } return retval; } void add(String newValue) { int elem = findElement(newValue); if( numberOfElements < maxNumberOfElements && elem == -1 ) { setElements[numberOfElements] = newValue; numberOfElements++; } } int getLength() { if ( setElements != null ) { return setElements.length; } else { return 0; } } String[] emptySet() { setElements = new String[0]; return setElements; } Boolean isFull() { Boolean True = new Boolean(true); Boolean False = new Boolean(false); if ( setElements.length == maxNumberOfElements ){ return True; } else { return False; } } Boolean isEmpty() { Boolean True = new Boolean(true); Boolean False = new Boolean(false); if ( setElements.length == 0 ) { return True; } else { return False; } } void remove(String newValue) { for ( int i = 0; i < setElements.length; i++) { if ( setElements[i].equals(newValue) ) { setElements = removeAt(i,setElements); } } } int isAMember(String element) { int retval = -1; for ( int i = 0; i < setElements.length; i++ ) { if (setElements[i] != null && setElements[i].equals(element)) { return retval = i; } } return retval; } void printSet() { for ( int i = 0; i < setElements.length; i++) { System.out.println("Member elements on index: "+ i +" " + setElements[i]); } } String[] getMember() { String[] tempArray = new String[setElements.length]; for ( int i = 0; i < setElements.length; i++) { if(setElements[i] != null) { tempArray[i] = setElements[i]; } } return tempArray; } Set union(Set x, Set y) { String[] newtemparray = new String[x.getLength]; newtemparray = x.getMember; return x; } } // This is the SetDemo class that will make use of our Set class class SetDemo { public static void main(String[] args) { //get input from keyboard BufferedReader keyboard; InputStreamReader reader; String temp = ""; reader = new InputStreamReader(System.in); keyboard = new BufferedReader(reader); try { System.out.println("Enter string element to be added" ); temp = keyboard.readLine( ); System.out.println("You entered " + temp ); } catch (IOException IOerr) { System.out.println("There was an error during input"); } /* ************************************************************************** * Test cases for our new created Set class. * ************************************************************************** */ Set setA = new Set(1,10,10); setA.add(temp); setA.add("b"); setA.add("b"); setA.add("hello"); setA.add("world"); setA.add("six"); setA.add("seven"); setA.add("b"); int size = setA.getLength(); System.out.println("Set size is: " + size ); Boolean isempty = setA.isEmpty(); System.out.println("Set is empty? " + isempty ); int ismember = setA.isAMember("sixb"); System.out.println("Element six is member of setA? " + ismember ); Boolean output = setA.isFull(); System.out.println("Set is full? " + output ); setA.printSet(); int index = setA.findElement("world"); System.out.println("Element b located on index: " + index ); setA.remove("b"); setA.emptySet(); int resize = setA.getLength(); System.out.println("Set size is: " + resize ); setA.printSet(); Set setB = new Set(0,10,10); Set SetA = setA.union(setB,setA); } } Ok the method in question will be the implementation of union. As such this: Set union(Set x, Set y) { String[] newtemparray = new String[x.getLength]; newtemparray = x.getMember; return x; } I got this error: symbol : variable getLength location: class Set String[] newtemparray = new String[x.getLength]; ^ d:\javaprojects\Set.java:122: cannot find symbol symbol : variable getMember location: class Set newtemparray = x.getMember; ^ 2 errors My approach for union would be: *) create temporary array of string with size of the object x length. *) store object x members to temporary array by looping the object and calling the getMember *) loop object y members and check if element exist against temporary array. *) discard if it exist/add if it is not there *) return obj x with the union array. thanks, lupin

    Read the article

  • Java constructor and modify the object properties at runtime

    - by lupin
    Note: This is an assignment Hi, I have the following class/constructor. import java.io.*; class Set { public int numberOfElements = 0; public String[] setElements = new String[5]; public int maxNumberOfElements = 5; // constructor for our Set class public Set(int numberOfE, int setE, int maxNumberOfE) { int numberOfElements = numberOfE; String[] setElements = new String[setE]; int maxNumberOfElements = maxNumberOfE; } // Helper method to shorten/remove element of array since we're using basic array instead of ArrayList or HashSet from collection interface :( static String[] removeAt(int k, String[] arr) { final int L = arr.length; String[] ret = new String[L - 1]; System.arraycopy(arr, 0, ret, 0, k); System.arraycopy(arr, k + 1, ret, k, L - k - 1); return ret; } int findElement(String element) { int retval = 0; for ( int i = 0; i < setElements.length; i++) { if ( setElements[i] != null && setElements[i].equals(element) ) { return retval = i; } retval = -1; } return retval; } void add(String newValue) { int elem = findElement(newValue); if( numberOfElements < maxNumberOfElements && elem == -1 ) { setElements[numberOfElements] = newValue; numberOfElements++; } } int getLength() { if ( setElements != null ) { return setElements.length; } else { return 0; } } String[] emptySet() { setElements = new String[0]; return setElements; } Boolean isFull() { Boolean True = new Boolean(true); Boolean False = new Boolean(false); if ( setElements.length == maxNumberOfElements ){ return True; } else { return False; } } Boolean isEmpty() { Boolean True = new Boolean(true); Boolean False = new Boolean(false); if ( setElements.length == 0 ) { return True; } else { return False; } } void remove(String newValue) { for ( int i = 0; i < setElements.length; i++) { if ( setElements[i].equals(newValue) ) { setElements = removeAt(i,setElements); } } } int isAMember(String element) { int retval = -1; for ( int i = 0; i < setElements.length; i++ ) { if (setElements[i] != null && setElements[i].equals(element)) { return retval = i; } } return retval; } void printSet() { for ( int i = 0; i < setElements.length; i++) { System.out.println("Member elements on index: "+ i +" " + setElements[i]); } } String[] getMember() { String[] tempArray = new String[setElements.length]; for ( int i = 0; i < setElements.length; i++) { if(setElements[i] != null) { tempArray[i] = setElements[i]; } } return tempArray; } Set union(Set x, Set y) { String[] newXtemparray = new String[x.getLength()]; String[] newYtemparray = new String[y.getLength()]; Set temp = new Set(1,20,20); newXtemparray = x.getMember(); newYtemparray = x.getMember(); for(int i = 0; i < newXtemparray.length; i++) { temp.add(newYtemparray[i]); } for(int j = 0; j < newYtemparray.length; j++) { temp.add(newYtemparray[j]); } return temp; } } // This is the SetDemo class that will make use of our Set class class SetDemo { public static void main(String[] args) { //get input from keyboard BufferedReader keyboard; InputStreamReader reader; String temp = ""; reader = new InputStreamReader(System.in); keyboard = new BufferedReader(reader); try { System.out.println("Enter string element to be added" ); temp = keyboard.readLine( ); System.out.println("You entered " + temp ); } catch (IOException IOerr) { System.out.println("There was an error during input"); } /* ************************************************************************** * Test cases for our new created Set class. * ************************************************************************** */ Set setA = new Set(1,10,10); setA.add(temp); setA.add("b"); setA.add("b"); setA.add("hello"); setA.add("world"); setA.add("six"); setA.add("seven"); setA.add("b"); int size = setA.getLength(); System.out.println("Set size is: " + size ); Boolean isempty = setA.isEmpty(); System.out.println("Set is empty? " + isempty ); int ismember = setA.isAMember("sixb"); System.out.println("Element six is member of setA? " + ismember ); Boolean output = setA.isFull(); System.out.println("Set is full? " + output ); setA.printSet(); int index = setA.findElement("world"); System.out.println("Element b located on index: " + index ); setA.remove("b"); setA.emptySet(); int resize = setA.getLength(); System.out.println("Set size is: " + resize ); setA.printSet(); Set setB = new Set(0,10,10); Set SetA = setA.union(setB,setA); SetA.printSet(); } } I have two question here, why I when I change the class property declaration to: class Set { public int numberOfElements; public String[] setElements; public int maxNumberOfElements; // constructor for our Set class public Set(int numberOfE, int setE, int maxNumberOfE) { int numberOfElements = numberOfE; String[] setElements = new String[setE]; int maxNumberOfElements = maxNumberOfE; } I got this error: \ javaprojects>java SetDemo Enter string element to be added a You entered a Exception in thread "main" java.lang.NullPointerException at Set.findElement(Set.java:30) at Set.add(Set.java:43) at SetDemo.main(Set.java:169) Second, on the union method, why the result of SetA.printSet still printing null, isn't it getting back the return value from union method? Thanks in advance for any explaination. lupin

    Read the article

  • Returning new object, overwrite the existing one in Java

    - by lupin
    Note: This is an assignment. Hi, Ok I have this method that will create a supposedly union of 2 sets. i mport java.io.*; class Set { public int numberOfElements; public String[] setElements; public int maxNumberOfElements; // constructor for our Set class public Set(int numberOfE, int setE, int maxNumberOfE) { this.numberOfElements = numberOfE; this.setElements = new String[setE]; this.maxNumberOfElements = maxNumberOfE; } // Helper method to shorten/remove element of array since we're using basic array instead of ArrayList or HashSet from collection interface :( static String[] removeAt(int k, String[] arr) { final int L = arr.length; String[] ret = new String[L - 1]; System.arraycopy(arr, 0, ret, 0, k); System.arraycopy(arr, k + 1, ret, k, L - k - 1); return ret; } int findElement(String element) { int retval = 0; for ( int i = 0; i < setElements.length; i++) { if ( setElements[i] != null && setElements[i].equals(element) ) { return retval = i; } retval = -1; } return retval; } void add(String newValue) { int elem = findElement(newValue); if( numberOfElements < maxNumberOfElements && elem == -1 ) { setElements[numberOfElements] = newValue; numberOfElements++; } } int getLength() { if ( setElements != null ) { return setElements.length; } else { return 0; } } String[] emptySet() { setElements = new String[0]; return setElements; } Boolean isFull() { Boolean True = new Boolean(true); Boolean False = new Boolean(false); if ( setElements.length == maxNumberOfElements ){ return True; } else { return False; } } Boolean isEmpty() { Boolean True = new Boolean(true); Boolean False = new Boolean(false); if ( setElements.length == 0 ) { return True; } else { return False; } } void remove(String newValue) { for ( int i = 0; i < setElements.length; i++) { if ( setElements[i] != null && setElements[i].equals(newValue) ) { setElements = removeAt(i,setElements); } } } int isAMember(String element) { int retval = -1; for ( int i = 0; i < setElements.length; i++ ) { if (setElements[i] != null && setElements[i].equals(element)) { return retval = i; } } return retval; } void printSet() { for ( int i = 0; i < setElements.length; i++) { if (setElements[i] != null) { System.out.println("Member elements on index: "+ i +" " + setElements[i]); } } } String[] getMember() { String[] tempArray = new String[setElements.length]; for ( int i = 0; i < setElements.length; i++) { if(setElements[i] != null) { tempArray[i] = setElements[i]; } } return tempArray; } Set union(Set x, Set y) { String[] newXtemparray = new String[x.getLength()]; String[] newYtemparray = new String[y.getLength()]; int len = newYtemparray.length + newXtemparray.length; Set temp = new Set(0,len,len); newXtemparray = x.getMember(); newYtemparray = x.getMember(); for(int i = 0; i < newYtemparray.length; i++) { temp.add(newYtemparray[i]); } for(int j = 0; j < newXtemparray.length; j++) { temp.add(newXtemparray[j]); } return temp; } Set difference(Set x, Set y) { String[] newXtemparray = new String[x.getLength()]; String[] newYtemparray = new String[y.getLength()]; int len = newYtemparray.length + newXtemparray.length; Set temp = new Set(0,len,len); newXtemparray = x.getMember(); newYtemparray = x.getMember(); for(int i = 0; i < newXtemparray.length; i++) { temp.add(newYtemparray[i]); } for(int j = 0; j < newYtemparray.length; j++) { int retval = temp.findElement(newYtemparray[j]); if( retval != -1 ) { temp.remove(newYtemparray[j]); } } return temp; } } // This is the SetDemo class that will make use of our Set class class SetDemo { public static void main(String[] args) { //get input from keyboard BufferedReader keyboard; InputStreamReader reader; String temp = ""; reader = new InputStreamReader(System.in); keyboard = new BufferedReader(reader); try { System.out.println("Enter string element to be added" ); temp = keyboard.readLine( ); System.out.println("You entered " + temp ); } catch (IOException IOerr) { System.out.println("There was an error during input"); } /* ************************************************************************** * Test cases for our new created Set class. * ************************************************************************** */ Set setA = new Set(0,10,10); setA.add(temp); setA.add("b"); setA.add("b"); setA.add("hello"); setA.add("world"); setA.add("six"); setA.add("seven"); setA.add("b"); int size = setA.getLength(); System.out.println("Set size is: " + size ); Boolean isempty = setA.isEmpty(); System.out.println("Set is empty? " + isempty ); int ismember = setA.isAMember("sixb"); System.out.println("Element sixb is member of setA? " + ismember ); Boolean output = setA.isFull(); System.out.println("Set is full? " + output ); //setA.printSet(); int index = setA.findElement("world"); System.out.println("Element b located on index: " + index ); setA.remove("b"); //setA.emptySet(); int resize = setA.getLength(); System.out.println("Set size is: " + resize ); //setA.printSet(); Set setB = new Set(0,10,10); setB.add("b"); setB.add("z"); setB.add("x"); setB.add("y"); Set setC = setA.union(setB,setA); System.out.println("Elements of setA"); setA.printSet(); System.out.println("Union of setA and setB"); setC.printSet(); } } The union method works a sense that somehow I can call another method on it but it doesn't do the job, i supposedly would create and union of all elements of setA and setB but it only return element of setB. Sample output follows: java SetDemo Enter string element to be added hello You entered hello Set size is: 10 Set is empty? false Element sixb is member of setA? -1 Set is full? true Element b located on index: 2 Set size is: 9 Elements of setA Member elements on index: 0 hello Member elements on index: 1 world Member elements on index: 2 six Member elements on index: 3 seven Union of setA and setB Member elements on index: 0 b Member elements on index: 1 z Member elements on index: 2 x Member elements on index: 3 y thanks, lupin

    Read the article

  • java converting int to short

    - by changed
    Hi I am calculating 16 bit checksum on my data which i need to send to server where it has to recalculate and match with the provided checksum. Checksum value that i am getting is in int but i have only 2 bytes for sending the value.So i am casting int to short while calling shortToBytes method. This works fine till checksum value is less than 32767 thereafter i am getting negative values. Thing is java does not have unsigned primitives, so i am not able to send values greater than max value of signed short allowed. How can i do this, converting int to short and send over the network without worrying about truncation and signed & unsigned int. Also on both the side i have java program running. private byte[] shortToBytes(short sh) { byte[] baValue = new byte[2]; ByteBuffer buf = ByteBuffer.wrap(baValue); return buf.putShort(sh).array(); } private short bytesToShort(byte[] buf, int offset) { byte[] baValue = new byte[2]; System.arraycopy(buf, offset, baValue, 0, 2); return ByteBuffer.wrap(baValue).getShort(); }

    Read the article

  • Java how can I add an accented "e" to a string?

    - by behrk2
    Hello, With the help of tucuxi from the existing post Java remove HTML from String without regular expressions I have built a method that will parse out any basic HTML tags from a string. Sometimes, however, the original string contains html hexadecimal characters like é (which is an accented e). I have started to add functionality which will translate these escaped characters into real characters. You're probably asking: Why not use regular expressions? Or a third party library? Unfortunately I cannot, as I am developing on a BlackBerry platform which does not support regular expressions and I have never been able to successfully add a third party library to my project. So, I have gotten to the point where any é is replaced with "e". My question now is, how do I add an actual 'accented e' to a string? Here is my code: public static String removeHTML(String synopsis) { char[] cs = synopsis.toCharArray(); String sb = new String(); boolean tag = false; for (int i = 0; i < cs.length; i++) { switch (cs[i]) { case '<': if (!tag) { tag = true; break; } case '>': if (tag) { tag = false; break; } case '&': char[] copyTo = new char[7]; System.arraycopy(cs, i, copyTo, 0, 7); String result = new String(copyTo); if (result.equals("&#x00E9")) { sb += "e"; } i += 7; break; default: if (!tag) sb += cs[i]; } } return sb.toString(); } Thanks!

    Read the article

  • Problem when copying array of different types using Arrays.copyOf

    - by Shervin
    I am trying to create a method that pretty much takes anything as a parameter, and returns a concatenated string representation of the value with some delimiter. public static String getConcatenated(char delim, Object ...names) { String[] stringArray = Arrays.copyOf(names, names.length, String[].class); //Exception here return getConcatenated(delim, stringArray); } And the actual method public static String getConcatenated(char delim, String ... names) { if(names == null || names.length == 0) return ""; StringBuilder sb = new StringBuilder(); for(int i = 0; i < names.length; i++) { String n = names[i]; if(n != null) { sb.append(n.trim()); sb.append(delim); } } //Remove the last delim return sb.substring(0, sb.length()-1).toString(); } And I have the following JUnit test: final String two = RedpillLinproUtils.getConcatenated(' ', "Shervin", "Asgari"); Assert.assertEquals("Result", "Shervin Asgari", two); //OK final String three = RedpillLinproUtils.getConcatenated(';', "Shervin", "Asgari"); Assert.assertEquals("Result", "Shervin;Asgari", three); //OK final String four = RedpillLinproUtils.getConcatenated(';', "Shervin", null, "Asgari", null); Assert.assertEquals("Result", "Shervin;Asgari", four); //OK final String five = RedpillLinproUtils.getConcatenated('/', 1, 2, null, 3, 4); Assert.assertEquals("Result", "1/2/3/4", five); //FAIL However, the test fails on the last part with the exception: java.lang.ArrayStoreException at java.lang.System.arraycopy(Native Method) at java.util.Arrays.copyOf(Arrays.java:2763) Can someone spot the error?

    Read the article

  • slowAES encryption and java descryption

    - by amnon
    Hi , I've tried to implement the same steps as discussed in AES .NET but with no success , i can't seem to get java and slowAes to play toghter ... attached is my code i'm sorry i can't add more this is my first time trying to deal with encryption would appreciate any help private static final String ALGORITHM = "AES"; private static final byte[] keyValue = getKeyBytes("12345678901234567890123456789012"); private static final byte[] INIT_VECTOR = new byte[16]; private static IvParameterSpec ivSpec = new IvParameterSpec(INIT_VECTOR); public static void main(String[] args) throws Exception { String encoded = encrypt("watson?"); System.out.println(encoded); } private static Key generateKey() throws Exception { Key key = new SecretKeySpec(keyValue, ALGORITHM); // SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM); // key = keyFactory.generateSecret(new DESKeySpec(keyValue)); return key; } private static byte[] getKeyBytes(String key) { byte[] hash = DigestUtils.sha(key); byte[] saltedHash = new byte[16]; System.arraycopy(hash, 0, saltedHash, 0, 16); return saltedHash; } public static String encrypt(String valueToEnc) throws Exception { Key key = generateKey(); Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding"); c.init(Cipher.ENCRYPT_MODE, key,ivSpec); byte[] encValue = c.doFinal(valueToEnc.getBytes()); String encryptedValue = new BASE64Encoder().encode(encValue); return encryptedValue; } public static String decrypt(String encryptedValue) throws Exception { Key key = generateKey(); Cipher c = Cipher.getInstance(ALGORITHM); c.init(Cipher.DECRYPT_MODE, key); byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedValue); byte[] decValue = c.doFinal(decordedValue); String decryptedValue = new String(decValue); return decryptedValue; } the bytes returned are different thanks in advance .

    Read the article

  • java array pass by reference does not work?

    - by stdnoit
    guys i thought almost all language including java pass array into function as reference (modifiable) but somehow it does not work here. and the testArray is still 1,2,3 with size of 3 strange enough, when if i change result[i] = 2 to a[1] =2; it work . it did pass by reference what is wrong with this code? at the end, i had a = result; (which update the a). did result get removed from stack. that is why a still get to the original a ? i am confused. thanks class Test { public static void main(String[] args) { int[] testArray = {1,2,3}; equalize(testArray, 6); System.out.println("test Array size :" + testArray.length); for(int i = 0; i < testArray.length; i++) System.out.println(testArray[i]); } public static void equalize(int[] a, int biggerSize) { if(a.length > biggerSize) throw new Error("Array size bigger than biggerSize"); int[] result = new int[biggerSize]; // System.arraycopy(a, 0, result, 0, a.length); // int array default value should be 0 for(int i = 0; i < biggerSize; i++) result[i] = 2; a = result; } }

    Read the article

  • Viewing the NetBeans Central Registry (Part 2)

    - by Geertjan
    Jens Hofschröer, who has one of the very best NetBeans Platform blogs (if you more or less understand German), and who wrote, sometime ago, the initial version of the Import Statement Organizer, as well as being the main developer of a great gear design & manufacturing tool on the NetBeans Platform in Aachen, commented on my recent blog entry "Viewing the NetBeans Central Registry", where the root Node of the Central Registry is shown in a BeanTreeView, with the words: "I wrapped that Node in a FilterNode to provide the 'position' attribute and the 'file extension'. All Children are wrapped too. Then I used an OutlineView to show these two properties. Great tool to find wrong layer entries." I asked him for the code he describes above and he sent it to me. He discussed it here in his blog, while all the code involved can be read below. The result is as follows, where you can see that the OutlineView shows information that my simple implementation (via a BeanTreeView) kept hidden: And so here is the definition of the Node. class LayerPropertiesNode extends FilterNode { public LayerPropertiesNode(Node node) { super(node, isFolder(node) ? Children.create(new LayerPropertiesFactory(node), true) : Children.LEAF); } private static boolean isFolder(Node node) { return null != node.getLookup().lookup(DataFolder.class); } @Override public String getDisplayName() { return getLookup().lookup(FileObject.class).getName(); } @Override public Image getIcon(int type) { FileObject fo = getLookup().lookup(FileObject.class); try { DataObject data = DataObject.find(fo); return data.getNodeDelegate().getIcon(type); } catch (DataObjectNotFoundException ex) { Exceptions.printStackTrace(ex); } return super.getIcon(type); } @Override public Image getOpenedIcon(int type) { return getIcon(type); } @Override public PropertySet[] getPropertySets() { Set set = Sheet.createPropertiesSet(); set.put(new PropertySupport.ReadOnly<Integer>( "position", Integer.class, "Position", null) { @Override public Integer getValue() throws IllegalAccessException, InvocationTargetException { FileObject fileEntry = getLookup().lookup(FileObject.class); Integer posValue = (Integer) fileEntry.getAttribute("position"); return posValue != null ? posValue : Integer.valueOf(0); } }); set.put(new PropertySupport.ReadOnly<String>( "ext", String.class, "Extension", null) { @Override public String getValue() throws IllegalAccessException, InvocationTargetException { FileObject fileEntry = getLookup().lookup(FileObject.class); return fileEntry.getExt(); } }); PropertySet[] original = super.getPropertySets(); PropertySet[] withLayer = new PropertySet[original.length + 1]; System.arraycopy(original, 0, withLayer, 0, original.length); withLayer[withLayer.length - 1] = set; return withLayer; } private static class LayerPropertiesFactory extends ChildFactory<FileObject> { private final Node context; public LayerPropertiesFactory(Node context) { this.context = context; } @Override protected boolean createKeys(List<FileObject> list) { FileObject folder = context.getLookup().lookup(FileObject.class); FileObject[] children = folder.getChildren(); List<FileObject> ordered = FileUtil.getOrder(Arrays.asList(children), false); list.addAll(ordered); return true; } @Override protected Node createNodeForKey(FileObject key) { AbstractNode node = new AbstractNode(org.openide.nodes.Children.LEAF, key.isFolder() ? Lookups.fixed(key, DataFolder.findFolder(key)) : Lookups.singleton(key)); return new LayerPropertiesNode(node); } } } Then here is the definition of the Action, which pops up a JPanel, displaying an OutlineView: @ActionID(category = "Tools", id = "de.nigjo.nb.layerview.LayerViewAction") @ActionRegistration(displayName = "#CTL_LayerViewAction") @ActionReferences({ @ActionReference(path = "Menu/Tools", position = 1450, separatorBefore = 1425) }) @Messages("CTL_LayerViewAction=Display XML Layer") public final class LayerViewAction implements ActionListener { @Override public void actionPerformed(ActionEvent e) { try { Node node = DataObject.find(FileUtil.getConfigRoot()).getNodeDelegate(); node = new LayerPropertiesNode(node); node = new FilterNode(node) { @Override public Component getCustomizer() { LayerView view = new LayerView(); view.getExplorerManager().setRootContext(this); return view; } @Override public boolean hasCustomizer() { return true; } }; NodeOperation.getDefault().customize(node); } catch (DataObjectNotFoundException ex) { Exceptions.printStackTrace(ex); } } private static class LayerView extends JPanel implements ExplorerManager.Provider { private final ExplorerManager em; public LayerView() { super(new BorderLayout()); em = new ExplorerManager(); OutlineView view = new OutlineView("entry"); view.addPropertyColumn("position", "Position"); view.addPropertyColumn("ext", "Extension"); add(view); } @Override public ExplorerManager getExplorerManager() { return em; } } }

    Read the article

  • Java loading user-specified classes at runtime

    - by user349043
    I'm working on robot simulation in Java (a Swing application). I have an abstract class "Robot" from which different types of Robots are derived, e.g. public class StupidRobot extends Robot { int m_stupidness; int m_insanityLevel; ... } public class AngryRobot extends Robot { float m_aggression; ... } As you can see, each Robot subclass has a different set of parameters. What I would like to do is control the simulation setup in the initial UI. Choose the number and type of Robots, give it a name, fill in the parameters etc. This is one of those times where being such a dinosaur programmer, and new to Java, I wonder if there is some higher level stuff/thinking that could help me here. So here is what I've got: (1) User Interface Scrolling list of Robot types on the left. "Add " and "<< Remove" buttons in the middle. Default-named scrolling list of Robots on the right. "Set Parameters" button underneath. (So if you wanted an AngryRobot, you'd select AngryRobot on the left list, click "Add" and "AngryRobot1" would show up on the right.) When selecting a Robot on the right, click "Set Parameters..." button which would call yet another model dialog where you'd fill in the parameters. Different dialog called for each Robot type. (2) Data structures an implementation As an end-product I think a HashMap would be most convenient. The keys would be Robot types and the accompanying object would be all of the parameters. The initializer could just retrieve each item one and a time and instantiate. Here's what the data structures would look like: enum ROBOT_TYPE {STUPID, ANGRY, etc} public class RobotInitializer { public ROBOT_TYPE m_type; public string m_name; public int[] m_int_params; public float[] m_float_params; etc. The initializer's constructor would create the appropriate length parameter arrays based on the type: public RobotInitializer(ROBOT_TYPE type, int[] int_array, float[] float_array, etc){ switch (type){ case STUPID: m_int_params = new int[STUPID_INT_PARAM_LENGTH]; System.arraycopy(int_array,0,m_int_params,0,STUPID_INT_PARAM_LENGTH); etc. Once all the RobotInitializers are instantiated, they are added to the HashMap. Iterating through the HashMap, the simulation initializer takes items from the Hashmap and instantiates the appropriate Robots. Is this reasonable? If not, how can it be improved? Thanks

    Read the article

1 2  | Next Page >