<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Saim Hafeez</title>
    <description>The latest articles on DEV Community by Saim Hafeez (@saimhafeez20).</description>
    <link>https://dev.to/saimhafeez20</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F609814%2Fa767993b-bc8b-4a58-b4cb-00b0a32c870f.jpeg</url>
      <title>DEV Community: Saim Hafeez</title>
      <link>https://dev.to/saimhafeez20</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/saimhafeez20"/>
    <language>en</language>
    <item>
      <title>Read and Sort Data Generically - Generics in Java</title>
      <dc:creator>Saim Hafeez</dc:creator>
      <pubDate>Sun, 01 Aug 2021 12:45:15 +0000</pubDate>
      <link>https://dev.to/saimhafeez20/read-and-sort-data-generically-java-generics-5bnk</link>
      <guid>https://dev.to/saimhafeez20/read-and-sort-data-generically-java-generics-5bnk</guid>
      <description>&lt;p&gt;I will demonstrate a Generic Java Class that will &lt;strong&gt;read and write the objects&lt;/strong&gt; any type of object passed to it (any &lt;strong&gt;Primitive Datatype or your custom classes&lt;/strong&gt; Like Explained in this example)&lt;/p&gt;

&lt;p&gt;Consider, you have a Class Named &lt;strong&gt;Students&lt;/strong&gt; in which there is &lt;strong&gt;name&lt;/strong&gt; and &lt;strong&gt;id&lt;/strong&gt; for a student.&lt;/p&gt;

&lt;p&gt;Now Also Consider another class named &lt;strong&gt;Employees&lt;/strong&gt; which also has &lt;strong&gt;name&lt;/strong&gt;, &lt;strong&gt;id&lt;/strong&gt; and &lt;strong&gt;workhours&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Now we want to implement a Generic class which will &lt;strong&gt;automatically writes the object to a file with file name begin the name of the class&lt;/strong&gt;. Now if there is already a &lt;strong&gt;.txt&lt;/strong&gt; file of that same class then it should &lt;strong&gt;append&lt;/strong&gt; the file with given new object.&lt;/p&gt;

&lt;p&gt;The Program should also be capable to &lt;strong&gt;read&lt;/strong&gt; the required file. The &lt;strong&gt;read()&lt;/strong&gt; method will &lt;strong&gt;return&lt;/strong&gt; the generic &lt;strong&gt;ArrayList&lt;/strong&gt; which we can type &lt;strong&gt;cast&lt;/strong&gt; to our required object like if we want to read the Students list stored in txt file then the read() method will return a Generic ArrayList and we can &lt;strong&gt;typecast&lt;/strong&gt; it to &lt;strong&gt;Students ArrayList&lt;/strong&gt; and Easily Use it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hence Completes our Requirement,&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;A Program the read and write any type of objects plus it writes the same type objects in their own text files (Appends if already present or create new if object of such type is written for the 1st time) making it awesome code that handles the files automatically.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h1&gt;
  
  
  QUICK THINGS TO KNOW BEFORE STARTING
&lt;/h1&gt;

&lt;p&gt;So First I have made two classes named &lt;strong&gt;Students.java&lt;/strong&gt; and &lt;strong&gt;Employees.java&lt;/strong&gt; and my main class is &lt;strong&gt;Main.java.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Main.java is shown at the end of this post, while Student.java &amp;amp;  Employees.java is not shown for the sake of complexity but if you do need to see them.&lt;/code&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Visit &lt;a href="https://saimhafeez.com/java-section/java-examples/advance/read-and-sort-data-generically-java-generics-saimhafeez-com/" rel="noopener noreferrer"&gt;Here&lt;/a&gt; for more detailed explanation with output explanation.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In &lt;strong&gt;Students.java&lt;/strong&gt; I have made a &lt;strong&gt;Constructor&lt;/strong&gt;, &lt;strong&gt;getters&lt;/strong&gt; and &lt;strong&gt;setters&lt;/strong&gt; for &lt;strong&gt;name&lt;/strong&gt; and &lt;strong&gt;id&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;IN Both Classes I Have Made A Method Named &lt;strong&gt;getData()&lt;/strong&gt; That Just Displays &lt;strong&gt;The Data (Name, Id, workhours etc)&lt;/strong&gt; of our Object.&lt;/p&gt;

&lt;h1&gt;
  
  
  Implementing Generic Class
&lt;/h1&gt;

&lt;h2&gt;
  
  
  Making A Generic Class
&lt;/h2&gt;

&lt;p&gt;I have made a class name &lt;strong&gt;GenericRead_Write.java&lt;/strong&gt; and I have &lt;strong&gt;parameterized&lt;/strong&gt; it by using &lt;strong&gt;&lt;/strong&gt;. We also created a field named &lt;strong&gt;object&lt;/strong&gt; with &lt;strong&gt;Type T&lt;/strong&gt;. Now in &lt;strong&gt;Constructor&lt;/strong&gt; I have set the &lt;strong&gt;instance object&lt;/strong&gt; with the locally passed &lt;strong&gt;object&lt;/strong&gt;. The Purpose of &lt;strong&gt;state&lt;/strong&gt; variable is explained in &lt;strong&gt;code&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class GenericRead_Write&amp;lt;T&amp;gt;{

    T object;
    int state  = 0;

    public GenericRead_Write(T object){
        this.object = object;
    }

    public void write(){/* CODE EXPLAINED NEXT */};
    public ArrayList&amp;lt;T&amp;gt; read(){/* CODE EXPLAINED NEXT */};
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Generic write() Method
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void write(){
        state = 1;
        String fileName = object.getClass().getName() + ".txt";
        ArrayList&amp;lt;T&amp;gt; list = new ArrayList&amp;lt;&amp;gt;();
        list = read();
        list.add(object);
        try {
            FileOutputStream file = new FileOutputStream(fileName);
            ObjectOutputStream outputFile = new ObjectOutputStream(file);
            for (T obj:
                 list) {
                outputFile.writeObject(obj);
            }


        }catch (Exception e){
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Explanation
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;String fileName = object.getClass().getName() + ".txt";&lt;/code&gt;&lt;br&gt;
This basically gets the name of the &lt;strong&gt;object&lt;/strong&gt; you passed in Generic Class with appending &lt;strong&gt;.txt&lt;/strong&gt; at the end of it. Next we will make a ArrayList with T as type parameter with name list.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;list = read()&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;At Forth Line we calls the &lt;strong&gt;read()&lt;/strong&gt; method to check if there is file with name &lt;strong&gt;fileName&lt;/strong&gt; is already present or not. If it is present then we read that file and store objects in list Assuming that there is not file present for Students or Employees [These are two test classes I made for the sake of demonstration] at this point, we add the object passed by the user to the ArrayList named list. And in Try and Catch Block we are make a object of &lt;strong&gt;FileOutStream&lt;/strong&gt; with file name being the &lt;strong&gt;filename&lt;/strong&gt; (it also automatically creates the file with that name if it is not present) and then we make an object for &lt;strong&gt;ObjectOutputStream&lt;/strong&gt; to write the object to file. And finally, By Using Foreach Loop we are writing the object to file. Before compiling, There is no file.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fsaimhafeez.com%2Fwp-content%2Fuploads%2F2021%2F08%2F1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fsaimhafeez.com%2Fwp-content%2Fuploads%2F2021%2F08%2F1.png" alt="Java-generics-output01-saimhafeez.com"&gt;&lt;/a&gt;&lt;br&gt;
After Comiling Programs creates a text file with our class name and package name being at start. See Below&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fsaimhafeez.com%2Fwp-content%2Fuploads%2F2021%2F08%2F2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fsaimhafeez.com%2Fwp-content%2Fuploads%2F2021%2F08%2F2.png" alt="Java-generics-output01-saimhafeez.com"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Generic read() Method
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public ArrayList&amp;lt;T&amp;gt; read() {
        String fileName = object.getClass().getName() + ".txt";
        ArrayList&amp;lt;T&amp;gt; list = new ArrayList&amp;lt;&amp;gt;();
        try{
            FileInputStream file = new FileInputStream(fileName);
            ObjectInputStream inputFile = new ObjectInputStream(file);
            boolean END_OF_FILE = false;
            while (!END_OF_FILE){
                try {
                    list.add((T) inputFile.readObject());
                }catch (EOFException e){
                    // When reaches END OF FILE we set the Boolean END_OF_FILE to TRUE
                    END_OF_FILE = true;
                }catch (Exception e){
                    JOptionPane.showMessageDialog(null, e.getMessage());
                }
            }

        }catch (FileNotFoundException j){
            if(state == 1){
                // Do Nothing... When state is 1 it means the write method is called
                // Since, the wite method will automatcally create new file is not found
                // So we don't require our program to show exception if read() is called from write()
            }else {
                // When state is 0 means the write() is not called so if file does not exits
                // in this case we show Error Message that file is not found
                JOptionPane.showMessageDialog(null, j.getMessage());
            }

        }catch (Exception e){
            JOptionPane.showMessageDialog(null, e.getMessage());
        }

        return list;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Explanation
&lt;/h3&gt;

&lt;p&gt;First of All this method will return a generic ArrayList so we used &lt;code&gt;ArrayList&amp;lt;T&amp;gt;&lt;/code&gt; as return type.&lt;/p&gt;

&lt;p&gt;Just like Previous we are creating a accurate &lt;strong&gt;fileName&lt;/strong&gt; and &lt;strong&gt;ArrayList&lt;/strong&gt; named &lt;strong&gt;list&lt;/strong&gt;. Now to read objects we will use object of &lt;strong&gt;FileInputStream&lt;/strong&gt; and pass it to &lt;strong&gt;objectInputStream&lt;/strong&gt;. Now we will make a boolean varibale named &lt;strong&gt;END_OF_FILE&lt;/strong&gt; which initially will be &lt;strong&gt;false&lt;/strong&gt; now in while loop we can &lt;strong&gt;not (!)&lt;/strong&gt; the &lt;strong&gt;END_OF_FILE&lt;/strong&gt; So, loop will run and read the objects and store them to &lt;strong&gt;ArrayList&lt;/strong&gt;. Now in &lt;strong&gt;catch statement&lt;/strong&gt; we can use &lt;strong&gt;EOFException&lt;/strong&gt; (END OF FILE Exception) and when we reach the end we can simply put the &lt;strong&gt;END_OF_FILE&lt;/strong&gt; equals to &lt;strong&gt;TRUE&lt;/strong&gt; Hence Loop will end. Now we can simply return the &lt;strong&gt;list&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Now at &lt;strong&gt;Main.java&lt;/strong&gt; we can access methods of our objects returned by this list by using type &lt;strong&gt;casting&lt;/strong&gt;.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fsaimhafeez.com%2Fwp-content%2Fuploads%2F2021%2F08%2F5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fsaimhafeez.com%2Fwp-content%2Fuploads%2F2021%2F08%2F5.png" alt="Java-read-saimhafeez.com"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  That's it!, for now
&lt;/h1&gt;

&lt;p&gt;&lt;em&gt;If you have any question, ask me in the comment section.&lt;br&gt;
Visit, &lt;a href="https://www.saimhafeez.com" rel="noopener noreferrer"&gt;my site&lt;/a&gt; for more Tutorials and examples&lt;/em&gt;&lt;/p&gt;

</description>
      <category>java</category>
      <category>algorithms</category>
      <category>generics</category>
    </item>
  </channel>
</rss>
