Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Monday, December 18, 2017

Java Interview Question: HashSet vs HashMap

HashSet

  1. HashSet class implements the Set interface
  2. In HashSet, we store objects(elements or values) e.g. If we have a HashSet of string elements then it could depict a set of HashSet elements: {“Hello”, “Hi”, “Bye”, “Run”}
  3. HashSet does not allow duplicate elements that mean you can not store duplicate values in HashSet.
  4. HashSet permits to have a single null value.
  5. HashSet is not synchronized which means they are not suitable for thread-safe operations until unless synchronized explicitly. 

HashMap


  1. HashMap class implements the Map interface
  2. HashMap is used for storing key & value pairs. In short, it maintains the mapping of key & value (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This is how you could represent HashMap elements if it has integer key and value of String type: e.g. {1->”Hello”, 2->”Hi”, 3->”Bye”, 4->”Run”}
  3. HashMap does not allow duplicate keys however it allows having duplicate values.
  4. HashMap permits single null key and any number of null values.
  5. HashMap is not synchronized which means they are not suitable for thread-safe operations until unless synchronized explicitly. 

Saturday, March 26, 2011

Escape Special chracters in java

Following code escaps the special meaning of characters before showing in XML or in view

 public static String escapeText(String s) {
   
    if (s.indexOf('&') != -1 || s.indexOf('<') != -1
     || s.indexOf('>') != -1 || s.indexOf('"') != -1
     || s.indexOf('\'') != -1 ) {
      StringBuffer result = new StringBuffer(s.length() + 6);
      for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (c == '&') result.append("&amp;");
        else if (c == '<') result.append("&lt;");
        else if (c == '"') result.append("&quot;");
        else if (c == '\'') result.append("&apos;");
        else if (c == '>') result.append("&gt;");
        else result.append(c);
      }
      return result.toString();  
    }
    else {
      return s;   
    }
        
  }

Wednesday, November 24, 2010

Generate a random alpha-numeric string in Java

By combinig use of Char array that having alphabets and numbers are an string of alphanumberic characters we can generate random alpha numberic strings in java.here is the exampls code that generate random alpha numberic string for the given length.

 /**
     * Generates alpha numeric random number for the given length.
     * for this it accounts lowercase alpha characters(a-z) and numbers(0-9)
     * @param length length of the alpha numeric random to be generated.
     * @return resulting random alpha numeric string for the given length.
     */
    public static String getAlphaNumbericRandom(int length) {
        //include lower case alpha(a-z) and numbers(0-9)
        String chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        int numberOfCodes = 0;//controls the length of alpha numberic string
        String code = "";
        while (numberOfCodes < length) {
            char c = chars.charAt((int) (Math.random() * chars.length()));
            code += c;
            numberOfCodes++;
        }
        System.out.println("Code is :" + code);
        return code;
    }

If we want to create 6 digit apha numberic random means we have call getAlphaNumbericRandom methods as

getAlphaNumbericRandom(6);

Wednesday, August 18, 2010

Creating a ZIP file in JAVA

Using ZipOutputStream and  Class in java.util.zip package we can craete an zip entry for the list of files.
The following gives the sample to create an zip file "outfile.zip" .This zip whill be created using the contents those given in the 'filenames' array.

1:  // These are the files to include in the ZIP file  
2:  String[] filenames = new String[]{"filename1", "filename2"};  
3:  // Create a buffer for reading the files  
4:  byte[] buf = new byte[1024];  
5:  try {  
6:    // Create the ZIP file  
7:    String outFilename = "outfile.zip";  
8:    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));  
9:    // Compress the files  
10:    for (int i=0; i<filenames.length; i++) {  
11:      FileInputStream in = new FileInputStream(filenames[i]);  
12:      // Add ZIP entry to output stream.  
13:      out.putNextEntry(new ZipEntry(filenames[i]));  
14:      // Transfer bytes from the file to the ZIP file  
15:      int len;  
16:      while ((len = in.read(buf)) > 0) {  
17:        out.write(buf, 0, len);  
18:      }  
19:      // Complete the entry  
20:      out.closeEntry();  
21:      in.close();  
22:    }  
23:    // Complete the ZIP file  
24:    out.close();  
25:  } catch (IOException e) {  
26:  }  

Source : http://www.exampledepot.com

Thursday, August 5, 2010

Getting multiple out parameters from oracle procedures

By using "DataReadQuery " when calling oracle stored procedure you can get values for multiple out parameters


here is the code snippet one i found in net when searching for this concept


 JpaEntityManager jpaEntityManager = JpaHelper.getEntityManager(em);  
 Session session = jpaEntityManager.getActiveSession();  
 StoredProcedureCall spc = new StoredProcedureCall();  
 spc.setProcedureName(“two_args_out”);  
 spc.addNamedArgument(“x”);  
 spc.addNamedOutputArgument(“y”);  
 spc.addNamedOutputArgument(“z”);  
 DataReadQuery query = new DataReadQuery();  
 query.setCall(spc);  
 query.addArgument(“x”);  
 List args = new ArrayList();  
 args.add(“Wouter”);  
 List results = (List) session.executeQuery(query, args);  
 DatabaseRecord record = (DatabaseRecord)results.get(0);  
 String y = (String) record.get(“y”);  
 String z = (String) record.get(“z”);  

Before this i have used ValueReadQuery to get result set from the procedure.but it doesn't help with multiple out parameters ,it returns only one.