Use hashCode() to compare strings instead of equalsIgnoreCase()

The HashCode method has a contract which says
" If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. "
Hence does it not make sense to use hashcode() method to compare two strings instead of using equals() method ? For example instead of using
String s = "One";
System.out.println("Strings equal = "+s.equals("Two"));
we can write
String s = "One";
System.out.println("Strings equal = "+(s.hashCode()=="Two".hashCode()));

Here is just a short list of strings with 3 characters that has the same hashcodes:
2NX and 2O9 has same hashCode 50556
3NX and 3O9 has same hashCode 51517
4NX and 4O9 has same hashCode 52478
5NX and 5O9 has same hashCode 53439
6NX and 6O9 has same hashCode 54400
7NX and 7O9 has same hashCode 55361
8NX and 8O9 has same hashCode 56322
9NX and 9O9 has same hashCode 57283
:NX and :O9 has same hashCode 58244
;NX and ;O9 has same hashCode 59205
<NX and <O9 has same hashCode 60166
=NX and =O9 has same hashCode 61127
NX and >O9 has same hashCode 62088?NX and ?O9 has same hashCode 63049
@NX and @O9 has same hashCode 64010
ANX and AO9 has same hashCode 64971
BNX and BO9 has same hashCode 65932
CNX and CO9 has same hashCode 66893
DNX and DO9 has same hashCode 67854
ENX and EO9 has same hashCode 68815
FNX and FO9 has same hashCode 69776
GNX and GO9 has same hashCode 70737
HNX and HO9 has same hashCode 71698
INX and IO9 has same hashCode 72659
JNX and JO9 has same hashCode 73620
KNX and KO9 has same hashCode 74581
LNX and LO9 has same hashCode 75542
MNX and MO9 has same hashCode 76503
NNX and NO9 has same hashCode 77464
ONX and OO9 has same hashCode 78425
PNX and PO9 has same hashCode 79386
QNX and QO9 has same hashCode 80347
RNX and RO9 has same hashCode 81308
SNX and SO9 has same hashCode 82269
TNX and TO9 has same hashCode 83230Kaj

Similar Messages

  • [svn:bz-trunk] 21292: Fix BLZ-639 - avoid the use of "==" when comparing strings.

    Revision: 21292
    Revision: 21292
    Author:   [email protected]
    Date:     2011-05-25 12:09:39 -0700 (Wed, 25 May 2011)
    Log Message:
    Fix BLZ-639 - avoid the use of "==" when comparing strings.  Just check for null explicitly.
    Ticket Links:
        http://bugs.adobe.com/jira/browse/BLZ-639
    Modified Paths:
        blazeds/trunk/modules/common/src/flex/messaging/config/ClientConfiguration.java

    Adobe has donated BlazeDS to the Apache Flex community, and the source code is hosted on the Apache Flex website in a GIT repository.
    http://flex.apache.org/dev-sourcecode.html

  • Using equals() to compare strings

    It was told in a previous post that when comparing two strings to use the equals()
    So rather than doing something like this
    package relationships;
    public class Starter {
         public static void main(String[] args){
              String foo = "foo";
              String bar = "bar";
              if(foo == bar){
                   System.out.println("Strings are logically equal");
              } else if(foo != bar){
                   System.out.println("Strings are not logically equal");
    }Where the console would output "Strings are not logically equal" How would I do this using the equals() (other then using else)
    package relationships;
    public class Starter {
         public static void main(String[] args){
              String foo = "foo";
              String bar = "bar";
              if(foo.equals(bar)){
                   System.out.println("Strings are logically equal");
              } else if( /* WHAT GOES HERE? */ ){
                   System.out.println("Strings are not logically equal");
    }I know to test if they are equal just to go like this foo.equals(bar) but what would I put in the else if?
    else if( /* WHAT GOES HERE? */ )

    Where the console would output "Strings are not
    logically equal" How would I do this using the
    equals() (other then using else)You don;t need anything else. If it is not true it is false there isn't a third boolean value of maybe or perhaps.

  • How come the JRE uses == to compare Strings?

    I was looking through the source of javax.swing.plaf.basic.BasicComboBoxUI and came across this:        public void propertyChange(PropertyChangeEvent e) {
                String propertyName = e.getPropertyName();
             JComboBox comboBox = (JComboBox)e.getSource();
                if ( propertyName == "model" ) {
                else if ( propertyName == "editor" && comboBox.isEditable() ) {
                else if ( propertyName == "editable" ) {
                else if ( propertyName == "enabled" ) {
                else if ( propertyName == "focusable" ) {
                else if ( propertyName == "maximumRowCount" ) {
                else if ( propertyName == "font" ) {
                else if ( propertyName == JComponent.TOOL_TIP_TEXT_KEY ) {
                else if ( propertyName == BasicComboBoxUI.IS_TABLE_CELL_EDITOR ) {
             else if (propertyName == "prototypeDisplayValue") {
             else if (propertyName == "renderer") {
            }So
    1) Is there a valid reason for the developer to have used == instead of .equals(...) to compare Strings?
    2) How does the code work consistently with this anomaly?
    Similar use of == and not .equals(...) is seen in many other swing classes.
    Doesn't affect me, but I would be interested to know if anyone can throw some light on this.
    Thanks, Darryl

    Darryl.Burke wrote:
    DeltaGeek, thank you for your response.
    Paul, I think I understand what you are saying, but the String reference propertyNamein this case comes from e.getPropertyName() from the PropertyChangeEvent class, not from within the BasicComboBoxUI class.
    I gather that all loaded classes share the same String pool, and that's how this works correctly. But in that case any comparison of a String variable to a literal String using == should also work.
    Then why the brouhaha about never using == to compare Strings?The key thing here is that the String returned by getPropertyName() must have come from a String literal. For example, in javax.swing.JComboBox:
    firePropertyChange( "maximumRowCount", oldCount, maximumRowCount );This string literal will be the same instance as the string literal in the code you posted.
    If they had instead done something like
    String s = "RowCount";
    boolean isMaximum = true;
    firePropertyChange((isMaximum ? "maximum" : "minimum") + s, oldCount, maximumRowCount );In this case, the String literal "maximumRowCount" is not used, but rather created from a concatenation at runtime, so it's likely that the comparison would fail.
    Note that the following would be the same String literal because this concatenation would be done at compile-time, not runtime:
    "maximum" + "RowCount"As for why, I agree with DeltaGeek: performance.

  • Compare Strings using JSTL

    How can I compare strings with JSTL? One string is a stored date and the other is a generated date. My goal is to set the correct date in a dropdown menu with date values (yyyy-MM-dd) by comparing the current date with the stored.
    Code
    <%
    Calendar cal = Calendar.getInstance(timezone, locale);
    Format fm = new SimpleDateFormat("yyyy-MM-dd");
    String date2 = (String) fm.format(cal.getTime()); %>
    <c:set var="date1" value="${mb.date}" />   // from database lookup (MySQL Date)
    <p><c:out value="${date1}"/>=<%=date2%>:<c:out value="${date1 == '<%=date2%>' }" /></p>The result is:
    2004-08-03 = 2004-08-03 : false

    well, about this:
    <%
    Calendar cal = Calendar.getInstance(timezone, locale);
    Format fm = new SimpleDateFormat("yyyy-MM-dd");
    String date2 = (String) fm.format(cal.getTime());
    pageContext.setAttribute("date2",date2);
    %>
    <c:set var="date1" value="${mb.date}" />   // from database lookup (MySQL Date)
    <p><c:out value="${date1}"/> .equals <%=date2%>:<c:out value="${date1eq date2}" /></p>I try to use the EL 'eq' like you would use '.equals()' in regular java, and EL '==' like regular java '==' And since we are comparing Strings here, which are objects, we would use .equals rather than ==, since == compares refernce and .equals compares value...

  • How to compare string in a case-insensitive manner using JavaScript?

    Hello everyone,
    Now I have a javascript to compare checkbox's value with user's input, but now seems it only can compare case-sensitively, does some one know if there is a function in javascript that it can compare string case-insensitively ?
    Here is my script :
    function findOffice(field)
    var name;
    name=prompt("What is the office name?");
    var l = field.length;
    for(var i = 0; i < l; i++)
    if(field.value==name)
    field[i].checked=true;
    field[i].focus();
    field[i].select();
    break;
    <input type="button" name="Find" value="Find And Select" onClick="findOffice(form1) >
    Thanks in advance !
    Rachel

    Thank you so much, I already solved the problem with your advice.
    You really have a beautiful mind, :-).
    I appreciate your help !
    Rachel

  • Simple question - compare Strings with SSIS expression language

    SSIS variables - strOne = YES, strTwo = YES. I want to compare strings using ssis expression language (ie inside a variable's expression box, constraint of task flow arrow etc).
    Will @strOne == @strTwo be true ? I hope its not like programming languages where you need to do
    @strOne.Equals(@strTwo) instead of ==. Also is @strOne == "YES" true ?

    ([User::strOne] == [User::Strtwo] ? True : False)
    The third variable created should be of type boolean if you're using above expression. if its of type int return 0 and 1 instead of False and true
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • SAP Soamanager WSDL generates n0:string instead of xsd:string in 7.3

    I´m using the Soamanager to create a Service for a Enterprise Service
    Provider. The web service is generated based on a custom function
    module. My intention is to consume a soap webservice via .net
    application. Actually this works fine with the legacy BW 7.0 system.
    But after we migrate the web service to the new BW 7.3 system, the web service interface is changed.
    I have taken a look at the generated WSDL-file from Soamanager, the soamanager
    generates the different type for string parameters. The
    Import/Export parameter should be of type xsd:string, but it is
    actually n0:string. but i need xsd:string for soap.
    I´ve tried several datatypes in function module, e.g string,
    char,....but always the same...n0:string instead of xsd:string.
    Can you help on how to change the sting type in wsdl?
    Thanks,

    How about a slight change to the xsd? Try with the following, it seems to work fine:
    <?xml version="1.0"?>
    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
       <xsd:element name="Orders" type="Orders"/>
       <xsd:complexType name="Orders">
          <xsd:choice minOccurs="0" maxOccurs="unbounded">
             <xsd:element name="ligne">
                <xsd:complexType>
                   <xsd:sequence>
                      <xsd:element name="Field1" type="xsd:string" />
                      <xsd:element name="Field2" type="xsd:string" />
                      <xsd:element name="Field3" type="xsd:string" />
                      <xsd:element name="Field4" type="xsd:string" />
                      <xsd:element name="Qte" type="xsd:string" />
                   </xsd:sequence>
                </xsd:complexType>
             </xsd:element>
          </xsd:choice>
       </xsd:complexType>
    </xsd:schema>
    You might also find this tool useful for testing such scenarios:
    http://xsdvalidation.utilities-online.info/
    By the way - how did you get the xsd that you are currently using?

  • Urgent Help required! - Storing the XML as String instead as a file

    Hi,
    I need urgent help on this.
    I have an XML file. I have used org.w3c.dom to build dom and manipulate the XML file.
    I have updated the values for some of the nodes and I have deleted some of the unwanted nodes.
    I am able to save the output of the DOM as another XML file using
    either transform class or XMLSerializer with OutputFormatter class.
    But my requirement is to save the output of the DOM into a String instead of a file.
    When I save it in String, I need to have the following XML decalration and DOCTYPE declration also with it.
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE Test SYSTEM "Test.dtd">
    Can anyone pls help me in this??
    Thanks in Advance. Expecting some inpputs pls....!
    Regards,
    Gayathri.

    hi,
    i think this is what u want
        public static String getXmlString(Document d) {
          StringWriter strResponse = null;
          try {
             OutputFormat format  = new OutputFormat(d);
             strResponse = new StringWriter();
             XMLSerializer serial = new XMLSerializer( strResponse, format );
             serial.asDOMSerializer();
             serial.serialize(d.getDocumentElement());
          catch (Exception e) {
            System.out.println(e.toString());
          return strResponse.toString();
    }HTH
    vasanth-ct

  • Problem: textbox leave empty string("") instead of null

    Hello, I have a problem with textboxes. By default, they always are initialized to null, but when I start entering and removing data from textboxes, many times they leave an empty string "" instead of null.
    And, of course, it's not the same a null value as an empty string and thus, I haven't got the expected result in queries to database.
    Thus, I always have to compare textbox values with "" and null. It's very tedious and not elegant solution. I would like to know if there is another way to get the values as null instead of empty strings.

    Yes. Once you entered and remove the text it will evaluated as you told .
    For ur case u can Try the condition as
    if ( instance !=null && instance.length !=0)
    be sure instance != null check b4 other wise u can get NullPointerException

  • How to use a custom comparator in a TableSorter?

    Hi,
    I want to use a custom comparator for sorting a table by a specific column.
    As you possibly know, the constructor for the TableSorter class looks like this:
    TableSorter(IWDTable table, IWDAction sortAction, Map comparators);
    As Map is an Interface I chose Hashmap as comparator container. So, I use the put(Key, Value) method to insert my own comparator into the Hashmap in order to deliver this Object to the TableSorter constructor.
    But there is an essential problem:
    I assume, that the column which is to be associated with my comparator is determined by the key of the Map object from the TableSorter constructor.
    Presuming this, <u>what should the map key be/look like?</u>
    An Integer counted from the columns? The column header as String? Whatever? Or am I on the wrong way?
    PS:
    Hours of search did not lead me to some kind of documentation or javadoc of the TableSorter class! This can't be, does someone have a link please?
    Thanks a lot for any help.

    (sorry Mrutyun, this did not help.)
    Ok, I solved it; let me share it with you:
    public class ExampleView
            public static void wdDoModifyView(IPrivateExampleView wdThis, IPrivateExampleView.IContextNode wdContext, com.sap.tc.webdynpro.progmodel.api.IWDView view, boolean firstTime)
                     * A custom Comparator class is used for sorting by Severity.
                     * An Object of it is delivered to an object of a Map class to be delivered to the TableSorter constructor.
                     * The Map class consists of key-value pairs, and the TableSorter must accept the Key of it
                     * because he uses it to assign the mapped Comparator to the column of the table to be sorted!
                     * And this is done with the ID of the Element, which shall be sorted with the Comparator, used as Map Key.
                     * All other columns of the assigned tables will be sorted by default Comparators.
                    IWDTable table = (IWDTable) view.getElement("[TableName]");
                    HashMap tableComps = new HashMap();
                    tableComps.put(view.getElement("[ColumnName]").getId(), new MyComp(wdContext.currentExampleElement())); //The map key value I looked for is the ID of the Element of the Column!
                    wdContext.current/*yourContextNode*/Element().setTableSort(
                            new TableSorter(table, wdThis.wdGetSortTableRowAction(),
                                    tableComps)); //Insert HashMap with the new Comparator
            public void onActionSortTableRow(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
            //@@begin onActionSortTableRow(ServerEvent)
                            wdContext.currentConfigurationElement().getTableSort().sort(wdEvent, wdContext.nodeOpenIncident());
            //@@end
    As you see, the Column which is to be sorted by the custom Comparator "MyComp", is clearly assigned to it. Thus, is will only be used when sorting by this column is done.
    The "inActionSort" method is as usual.
    My Comparator sorts a column which contains variables of a "SimpleType" with an enumeration. (If you need help with this, feel free to write me.) To achieve this, the Comparator needs to know what this SimpleType consists of. That's why I deliver this Element per Constructor to it.
    public class MyComp implements Comparator
         MappedNodeElement element;
         public SeverityComp(I/*one*/Element element)
              this.element = element;
         public SeverityComp(I/*another*/Element element)
              this.element = element;
         public int compare(Object severity1, Object severity2)
    Because MappedNodeElement is such abstract, it can be used by several different Tables, provided they use the same SimpleType.
    Concerning my quest for this resolution, I hope this is helpful.
    null

  • Comparing string delimited by semicolon in a column with another string

    Hi
    I have requirement like comparing a column which contains the string delimited by semi colon with a string delimited by semicolon. i.e. comparing the multiple values with multiple values.for this purpose i am using the following code
    select ams.application_id,it_mgmt_chain
    FROM tb_ams038_application ams,THE
    (SELECT CAST
    (Appmgmt_Str_To_Table
    (NVL (ams.it_mgmt_chain,
    ) AS appmgmt_tabletype_string
    FROM DUAL
    AND (COLUMN_VALUE IN ( SELECT COLUMN_VALUE
    FROM THE
    (SELECT CAST
    (Appmgmt_Str_To_Table
    (nvl(NVL (replace('1234;8383;83939;93939',',',';'),
    ams.it_mgmt_chain
    ) AS appmgmt_tabletype_string
    FROM DUAL
    here in the above it_mgmt_chain has the string containing numbers seperated by semi colon. and the Appmgmt_Str_To_Table function used to split the string and return it in the form of list. and appmgmt_tabletype_string is a varray which is created for spliting and storing purpose.
    Can anyone please suggest the best way to do this task as the above code is giving a performance issue.

    This example uses a "|" not a semicolon but it leverages the REGEXP_SUBSTR, SUBSTR, LENGTH to perform a parsing action.
    http://blog.mclaughlinsoftware.com/plsql-programming/a-result-cache-function-returning-a-collection/
    You may wish to remove the "THE" and replace it with "TABLE" too. Good luck.

  • Comparing string in select query

    Hi,
    select single *
           from mara
           where <b>matnr = wa-matnr</b>.
    Here matnr is char18. Can we compare string like this?
    When <b>wa-matnr</b> is in <b>lower case</b> it is setting sy-subrc = 4, even though the matnr exists in mara. When converted to upper case and used it is setting sy-subrc = 0.
    Is there any other solution for the problem? I have checked out with matnr's conversion routine. It is also not working.

    just try  dat way...
    <b>ex...</b>
    data:wa_matnr like mara-matnr.
    data:wa_matnr1 like mara-matnr.
    data: gv_matnr like mara-matnr.
    wa_matnr = 'comptest'.
    CALL FUNCTION 'TERM_TRANSLATE_TO_UPPER_CASE'
      EXPORTING
       LANGU                     = SY-LANGU
        TEXT                     = wa_matnr
    IMPORTING
       TEXT_UC                   = wa_matnr1
    EXCEPTIONS
      NO_LOCALE_AVAILABLE       = 1
      OTHERS                    = 2
    IF SY-SUBRC <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
            WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    select single matnr
    from mara into gv_matnr
    where matnr = wa_matnr or matnr = wa_matnr1.
    write : gv_matnr.

  • Using JSplitPane for Comparing two Files/Contents

    Hi Java Gurus,
    I want to develope a Comparison tool which compares 2 jar files and report the difference in a user friendly manner. Everything is fine and i selected the JSplitPane to display the difference report. I face some problems in doing it exactly simillar way of presenting like a Comparison tools which is there in VSS.
    I created 2 panels and added in a splitpane.
    one panel contains the content of first jar file and another panel contains the content of second jar file.
    The content are added in a textarea and the textarea is added to a scrollpane, which is added to the panel.
    If i fix some size to Textarea, when i expand the Splitpane, the size is not getting expanded accordingly.
    if i remove the size for textarea, the content is not displayed.
    Can anyon give some suggestion.
    Have anybody developed a GUI using JSplitPane simmilar to any Difference Tool simillar to VSS.
    expecting your replies.
    Raffi

    Hi,
    Eventhough the left and right pane are not synchronized, It is showing the Differences.
    I have changed the JTextArea to JTextPane to have control on each of the String i am inserting.
    It is fine. but when i am doing the comparison for the second time, i am removing the content of the Document (of the JTextPane) and adding the new Content to the Document (of the JTextPane).
    While i am printing the length and text after removing the Old Content (in console), i am getting 0, "". But in the GUI old content are not removed and new content keeps on appending, eventhough i do updateUI() and validate().
    Is that a BUG of JTextPane?????????????
    Can any One Figure it out.
    My Code is Here:
    import java.io.*;
    import java.util.zip.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    * put your documentation comment here
    public class CheckZipFile extends JFrame {
    private JLabel firstZip = null;
    private JLabel secondZip = null;
    private JTextField firstZipName = null;
    private JTextField secondZipName = null;
    private JButton compare = null;
    private JPanel mainPanel = null;
    private JFileChooser fileChooser = null;
    private JButton chooseButton1 = null;
    private JButton chooseButton2 = null;
    private StringBuffer buffer = null;
    private StringBuffer buffer1 = null;
    private StringBuffer buffer2 = null;
    private ApolloFileFilter zipFilter;
    private JTextPane first = null;
    private JTextPane second = null;
    private Document doc1 = null;
    private Document doc = null;
    * put your documentation comment here
    public CheckZipFile () {
    initialize();
    buildGUI();
    addWindowListener();
    setLookAndFeel();
    this.pack();
    * put your documentation comment here
    private void initialize () {
    buffer = new StringBuffer();
    buffer1 = new StringBuffer();
    buffer2 = new StringBuffer();
    zipFilter = new ApolloFileFilter(new String[] {
    "zip", "jar"
    }, "ZIP and JAR Files");
    fileChooser = new JFileChooser(new File("c:\\"));
    //fileChooser.setAcceptAllFileFilterUsed(false);
    fileChooser.addChoosableFileFilter(zipFilter);
    * put your documentation comment here
    private void setLookAndFeel () {
    try {
    UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    SwingUtilities.updateComponentTreeUI(this);
    if (fileChooser != null) {
    SwingUtilities.updateComponentTreeUI(fileChooser);
    } catch (UnsupportedLookAndFeelException exc) {
    System.out.println("Unsupported Look And Feel:" +
    exc);
    } catch (IllegalAccessException exc) {
    System.out.println("IllegalAccessException Error:"
    + exc);
    } catch (ClassNotFoundException exc) {
    System.out.println("ClassNotFoundException Error:"
    + exc);
    } catch (InstantiationException exc) {
    System.out.println("InstantiateException Error:"
    + exc);
    * put your documentation comment here
    private void buildGUI () {
    mainPanel = createPanel();
    this.getContentPane().setLayout(new BorderLayout());
    this.getContentPane().add(mainPanel, BorderLayout.CENTER);
    this.getContentPane().add(createDifferencePanel(), BorderLayout.SOUTH);
    this.setSize(700, 450);
    SwingUtilities.updateComponentTreeUI(this);
    * put your documentation comment here
    * @return
    private JPanel createPanel () {
    JPanel main = new JPanel() {
    * put your documentation comment here
    * @return
    public Dimension getPrefferedSize () {
    return new Dimension(300, 90);
    main.setLayout(new GridLayout(3, 3));
    firstZip = new JLabel("First Jar/Zip File:") {
    * put your documentation comment here
    * @return
    public Dimension getPrefferedSize () {
    return new Dimension(100, 30);
    main.add(firstZip);
    firstZipName = new JTextField() {
    * put your documentation comment here
    * @return
    public Dimension getPrefferedSize () {
    return new Dimension(100, 30);
    main.add(firstZipName);
    chooseButton1 = new JButton("Choose File 1") {
    * put your documentation comment here
    * @return
    public Dimension getPrefferedSize () {
    return new Dimension(100, 30);
    main.add(chooseButton1);
    chooseButton1.addActionListener(new ButtonListener());
    secondZip = new JLabel("Second Jar/Zip File:") {
    * put your documentation comment here
    * @return
    public Dimension getPrefferedSize () {
    return new Dimension(100, 30);
    main.add(secondZip);
    secondZipName = new JTextField() {
    * put your documentation comment here
    * @return
    public Dimension getPrefferedSize () {
    return new Dimension(100, 30);
    main.add(secondZipName);
    chooseButton2 = new JButton("Choose File 2") {
    * put your documentation comment here
    * @return
    public Dimension getPrefferedSize () {
    return new Dimension(100, 30);
    main.add(chooseButton2);
    chooseButton2.addActionListener(new ButtonListener());
    JLabel temp1 = new JLabel("") {
    * put your documentation comment here
    * @return
    public Dimension getPrefferedSize () {
    return new Dimension(100, 30);
    main.add(temp1);
    compare = new JButton("Compare") {
    * put your documentation comment here
    * @return
    public Dimension getPrefferedSize () {
    return new Dimension(100, 30);
    compare.addActionListener(new ButtonListener());
    main.add(compare);
    JLabel temp2 = new JLabel("") {
    * put your documentation comment here
    * @return
    public Dimension getPrefferedSize () {
    return new Dimension(100, 30);
    main.add(temp2);
    return main;
    * put your documentation comment here
    * @param fileContent1
    * @param fileContent2
    private void updateGUI (String fileContent1, String fileContent2) {
    System.out.println("Came here UpdateGUI");
    updateDifferencePanel(fileContent1, fileContent2);
    System.out.println("Came here UpdateGUI after call");
    SwingUtilities.updateComponentTreeUI(this);
    * put your documentation comment here
    * @return
    private JSplitPane createDifferencePanel () {
    JPanel firstPanel = new JPanel() {
    * put your documentation comment here
    * @return
    public Dimension getPrefferedSize () {
    return new Dimension(350, 360);
    first = new JTextPane();
    initStylesForTextPane(first);
    doc1 = first.getDocument();
    JScrollPane scroll1 = new JScrollPane(first);
    scroll1.setPreferredSize(new Dimension(325, 360));
    scroll1.setMinimumSize(new Dimension(100, 100));
    firstPanel.add(scroll1);
    first.updateUI();
    first.validate();
    JPanel secondPanel = new JPanel() {
    * put your documentation comment here
    * @return
    public Dimension getPrefferedSize () {
    return new Dimension(350, 360);
    second = new JTextPane();
    initStylesForTextPane(second);
    doc = second.getDocument();
    JScrollPane scroll2 = new JScrollPane(second);
    scroll2.setPreferredSize(new Dimension(325, 360));
    scroll2.setMinimumSize(new Dimension(100, 100));
    secondPanel.add(scroll2);
    second.updateUI();
    second.validate();
    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
    firstPanel, secondPanel);
    splitPane.setDividerLocation(0.5);
    splitPane.updateUI();
    splitPane.validate();
    splitPane.setPreferredSize(new Dimension(700, 360));
    return splitPane;
    * put your documentation comment here
    * @param fileContent1
    * @param fileContent2
    private void updateDifferencePanel (String fileContent1,
    String fileContent2) {
    System.out.println("Came here");
    try {
    doc1 = first.getDocument();
    System.out.println("Text bef: " + first.getText());
    System.out.println("Length bef: " + doc1.getLength());
    doc1.remove(0, doc1.getLength());
    System.out.println("Length aft: " + doc1.getLength());
    System.out.println("Text aft: " + first.getText());
    doc1.insertString(doc1.getLength(), "test", first.getStyle("regular"));
    first.updateUI();
    first.validate();
    } catch (BadLocationException ble1) {
    ble1.printStackTrace();
    StringTokenizer tokens1 = new StringTokenizer(fileContent1,
    String token1 = "";
    String text1 = "";
    String differs1 = "false";
    int indexOfColon1 = -1;
    int count1 = 0;
    while (tokens1.hasMoreTokens()) {
    token1 = (String)tokens1.nextToken();
    count1++;
    indexOfColon1 = token1.lastIndexOf(":");
    text1 = token1.substring(0, indexOfColon1);
    differs1 = token1.substring(indexOfColon1 + 1);
    try {
    if (count1 == 1)
    System.out.println("Start: " + doc1.getLength());
    if (differs1.equals("true"))
    doc1.insertString(doc1.getLength(), text1
    + ":", first.getStyle("bold"));
    else
    doc1.insertString(doc1.getLength(), text1
    + ":", first.getStyle("regular"));
    if ((count1%3) == 0)
    doc1.insertString(doc1.getLength(), "\n",
    first.getStyle("regular"));
    } catch (BadLocationException ble1) {
    ble1.printStackTrace();
    first.updateUI();
    first.validate();
    try {
    System.out.println("Length bef: " + doc.getLength());
    doc.remove(0, doc.getLength());
    System.out.println("Length aft: " + doc.getLength());
    second.updateUI();
    second.validate();
    } catch (BadLocationException ble1) {
    ble1.printStackTrace();
    StringTokenizer tokens = new StringTokenizer(fileContent2,
    String token = "";
    String text = "";
    String differs = "false";
    int indexOfColon = -1;
    int count = 0;
    while (tokens.hasMoreTokens()) {
    token = (String)tokens.nextToken();
    count++;
    indexOfColon = token.lastIndexOf(":");
    text = token.substring(0, indexOfColon);
    differs = token.substring(indexOfColon + 1);
    try {
    if (differs.equals("true"))
    doc.insertString(doc.getLength(), text +
    ":", second.getStyle("bold"));
    else
    doc.insertString(doc.getLength(), text +
    ":", second.getStyle("regular"));
    if ((count%3) == 0)
    doc.insertString(doc.getLength(), "\n",
    second.getStyle("regular"));
    } catch (BadLocationException ble) {
    ble.printStackTrace();
    second.updateUI();
    second.validate();
    * put your documentation comment here
    * @param textPane
    protected void initStylesForTextPane (JTextPane textPane) {
    //Initialize some styles.
    Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
    Style regular = textPane.addStyle("regular", def);
    StyleConstants.setFontFamily(def, "SansSerif");
    Style s = textPane.addStyle("italic", regular);
    StyleConstants.setItalic(s, true);
    s = textPane.addStyle("bold", regular);
    StyleConstants.setBold(s, true);
    s = textPane.addStyle("small", regular);
    StyleConstants.setFontSize(s, 10);
    s = textPane.addStyle("large", regular);
    StyleConstants.setFontSize(s, 16);
    s = textPane.addStyle("icon", regular);
    StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);
    StyleConstants.setIcon(s, new ImageIcon("images/Pig.gif"));
    s = textPane.addStyle("button", regular);
    StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);
    JButton button = new JButton(new ImageIcon("images/sound.gif"));
    button.setMargin(new Insets(0, 0, 0, 0));
    button.addActionListener(new ActionListener() {
    * put your documentation comment here
    * @param e
    public void actionPerformed (ActionEvent e) {
    Toolkit.getDefaultToolkit().beep();
    StyleConstants.setComponent(s, button);
    * put your documentation comment here
    private void addWindowListener () {
    this.addWindowListener(new WindowAdapter() {
    * put your documentation comment here
    * @param we
    public void windowClosed (WindowEvent we) {
    CheckZipFile.this.dispose();
    System.exit(1);
    * put your documentation comment here
    * @param we
    public void windowClosing (WindowEvent we) {
    CheckZipFile.this.dispose();
    System.exit(1);
    * put your documentation comment here
    * @param argv[]
    * @exception Exception
    public static void main (String argv[]) throws Exception {
    CheckZipFile compareZip = new CheckZipFile();
    compareZip.pack();
    compareZip.setVisible(true);
    * put your documentation comment here
    public class ButtonListener
    implements ActionListener {
    * put your documentation comment here
    * @param ae
    public void actionPerformed (ActionEvent ae) {
    if (ae.getSource() == chooseButton1) {
    int retval = fileChooser.showDialog(CheckZipFile.this,
    "Select");
    if (retval == JFileChooser.APPROVE_OPTION) {
    File theFile = fileChooser.getSelectedFile();
    if (theFile != null) {
    File[] files = fileChooser.getSelectedFiles();
    if (fileChooser.isMultiSelectionEnabled()
    && files != null && files.length > 1) {
    String filenames = "";
    for (int i = 0; i < files.length; i++) {
    filenames = filenames + "\n"
    + files.getPath();
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "You chose these files: \n"
    + filenames + "\n Multiple Selection Should not be done here");
    else if (theFile.isDirectory()) {
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "You chose this directory: "
    + fileChooser.getSelectedFile().getPath()
    + "\n Please select a Zip File or jar File");
    else {
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "You chose this file: " +
    fileChooser.getSelectedFile().getPath());
    firstZipName.setText(fileChooser.getSelectedFile().getPath());
    return;
    else if (retval == JFileChooser.CANCEL_OPTION) {
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "User cancelled operation. No file was chosen.");
    else if (retval == JFileChooser.ERROR_OPTION) {
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "An error occured. No file was chosen.");
    else {
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "Unknown operation occured.");
    if (ae.getSource() == chooseButton2) {
    int retval = fileChooser.showDialog(CheckZipFile.this,
    "Select");
    if (retval == JFileChooser.APPROVE_OPTION) {
    File theFile = fileChooser.getSelectedFile();
    if (theFile != null) {
    File[] files = fileChooser.getSelectedFiles();
    if (fileChooser.isMultiSelectionEnabled()
    && files != null && files.length > 1) {
    String filenames = "";
    for (int i = 0; i < files.length; i++) {
    filenames = filenames + "\n"
    + files[i].getPath();
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "You chose these files: \n"
    + filenames + "\n Multiple Selection Should not be done here");
    else if (theFile.isDirectory()) {
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "You chose this directory: "
    + fileChooser.getSelectedFile().getPath()
    + "\n Please select a Zip File or jar File");
    else {
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "You chose this file: " +
    fileChooser.getSelectedFile().getPath());
    secondZipName.setText(fileChooser.getSelectedFile().getPath());
    return;
    else if (retval == JFileChooser.CANCEL_OPTION) {
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "User cancelled operation. No file was chosen.");
    else if (retval == JFileChooser.ERROR_OPTION) {
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "An error occured. No file was chosen.");
    else {
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "Unknown operation occured.");
    if (ae.getSource() == compare) {
    String file1 = firstZipName.getText();
    String file2 = secondZipName.getText();
    if (file1 == null || file2 == null) {
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "Enter / Select the Files to be compared");
    return;
    if (file1.equals("") || file2.equals("")) {
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "Enter / Select the Files to be compared");
    return;
    try {
    ZipFile zip1 = new ZipFile(file1);
    ZipFile zip2 = new ZipFile(file2);
    int size1 = zip1.size();
    int size2 = zip2.size();
    if (size1 != size2) {
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "Size of both the jars are not same");
    return;
    Enumeration entries1 = zip1.entries();
    Enumeration entries2 = zip2.entries();
    ZipEntry entry1 = null;
    ZipEntry entry2 = null;
    String name1 = "";
    String name2 = "";
    long filesize1 = 0;
    long filesize2 = 0;
    long time1;
    long time2;
    //StringBuffer detail = new StringBuffer();
    boolean nameDiffers = false;
    boolean sizeDiffers = false;
    boolean timeDiffers = false;
    buffer.append(file1 + "\t\t\t" + file2 +
    "\n______________________________________________________________________\n");
    //buffer1.append("\t\t" + file1 + "\n");
    //buffer2.append("\t\t" + file2 + "\n");
    int length = buffer.length();
    for (int x = 0; x < size1; x++) {
    nameDiffers = false;
    sizeDiffers = false;
    timeDiffers = false;
    entry1 = (ZipEntry)entries1.nextElement();
    entry2 = (ZipEntry)entries2.nextElement();
    name1 = entry1.getName();
    name2 = entry2.getName();
    filesize1 = entry1.getSize();
    filesize2 = entry2.getSize();
    time1 = entry1.getTime();
    time2 = entry2.getTime();
    if (!name1.equals(name2)) {
    //System.out.println("Name of the Entries in both the Jars are not same:\n"+ entry1.getName() + " : " + entry2.getName() );
    nameDiffers = true;
    //return;
    //else
    //     System.out.println("Name: " +entry1.getName());
    if (filesize1 != filesize2) {
    //System.out.println("Size of the Entries in both the Jars are not same:\n"+ entry1.getSize() + " : " + entry2.getSize() );
    sizeDiffers = true;
    //return;
    if (time1 != time2) {
    //System.out.println("Time of the Entries in both the Jars are not same:\n"+ entry1.getTime() + " : " + entry2.getTime() );
    timeDiffers = true;
    //return;
    if (nameDiffers || sizeDiffers || timeDiffers) {
    if (filesize1 != 0 && filesize2 !=
    0) {
    buffer.append(name1 + ":" +
    filesize1 + ":" + new java.util.Date(time1)
    + "\t" + name2 + ":"
    + filesize2 + ":" +
    new java.util.Date(time2)
    + "\n");
    buffer1.append(name1 + ":" +
    nameDiffers + ";" +
    filesize1 + ":" + sizeDiffers
    + ";" + new java.util.Date(time1).toString()
    + ":" + timeDiffers +
    buffer2.append(name2 + ":" +
    nameDiffers + ";" +
    filesize2 + ":" + sizeDiffers
    + ";" + new java.util.Date(time2).toString()
    + ":" + timeDiffers +
    if (length == buffer.length())
    JOptionPane.showMessageDialog(CheckZipFile.this,
    "Both the Zip / Jar Files are Identical");
    else {
    getToolkit().beep();
    //System.out.println(buffer.toString());
    updateGUI(buffer1.toString(), buffer2.toString());
    getToolkit().beep();
    } catch (Exception ex) {
    ex.printStackTrace();

  • Compare string in different line in text file

    I am new to java and I need a simple example to compare string in file text by for loop
    file.txt:
    A78802 D06VAIS060253113 WKNEUP751346577450
    A77802 D06VAIS060253113 WKNEUP751346577450
    A76802 D06VAIS060253925 WKNEUP751346577450
    A78802 D06VAIS075253698 WKNEGE226375082796
    A73802 D06VAIS116253222 WKNEFB227345305299
    dataString = TextIO.getln();
    A=dataString.substring(25,42);
    B=dataString.substring(195,203);
    C=dataString.substring(171,186);
    I WANT COPMPARE IN LINE 1 POSITION 20 TO LINE 2 POSITION 20 BY LOOPS ALL THE LINE IN TEXT FILE

    what have you tried so far?
    Also, when posting your code, please use code tags so that your code will retain its formatting and be readable. To do this, either use the "code" button at the top of the forum Message editor or place the tag &#91;code] at the top of your block of code and the tag &#91;/code] at the bottom, like so:
    &#91;code]
      // your code block goes here.
    &#91;/code]

Maybe you are looking for

  • How can I print from the ipad

    I need to be able to print boarding passes the night before a flight and an occasional form sent through email. Trying to see if I can stop carrying my laptop.  I can usually find a printer with USB connection so I am guessing I just buy the camera c

  • USEREXIT_CHECK_XVBEP_FOR_DELET USING US_EXIT

    Can anyone tell me under what conditions this user exit in MV45AFZB gets hit?  I would expect it to get hit when a line is being deleted from VBEP, but it does not seem to be hitting it. My requirement is to find a place to update a user field in vba

  • Sending mail to Junk crashes Mail

    When a piece of junk mail makes it to my inbox and I select it and press "Junk", Mail.app freezes and I have to restart. It does this consistently. With my internet connection off, I have tried to reset Junk in preferences, but the problem will not g

  • Mail appearing in duplicate

    Mail received in duplicate. How can I sliminate this ?

  • Missing movies in project since iOS 8 and iCloud Photo Library

    Hi, I've been to Europe this summer and created a movie in iMovie for iOS. That was when iOS 7.1.2 was the most current release. Today, I wanted to finish up my project. I'm currently running on iPad air, iOS 8.0.2, latest release of iMovie and iClou