<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Mats Karlsson</title>
	<atom:link href="https://www.matskarlsson.se/feed" rel="self" type="application/rss+xml" />
	<link>https://www.matskarlsson.se</link>
	<description>Software development blog</description>
	<lastBuildDate>Wed, 12 Mar 2014 14:33:03 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.5.14</generator>
	<item>
		<title>Testable object wrapper</title>
		<link>https://www.matskarlsson.se/blog/testable-object-wrapper</link>
					<comments>https://www.matskarlsson.se/blog/testable-object-wrapper#respond</comments>
		
		<dc:creator><![CDATA[Mats Karlsson]]></dc:creator>
		<pubDate>Wed, 12 Mar 2014 19:32:24 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Unit Test]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[unit-test]]></category>
		<guid isPermaLink="false">http://www.matskarlsson.se/?p=85</guid>

					<description><![CDATA[Have started experimenting with a way of wrapping the &#8216;system under test&#8217; in a wrapper-class that also contains the mocked dependencies. The class is instantiated the same way as Brad Wilson&#8217;s Testable Object Pattern with a static Create method. The big difference from his pattern is that the system under test is a public Sut-property instead [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Have started experimenting with a way of wrapping the &#8216;system under test&#8217; in a wrapper-class that also contains the mocked dependencies. The class is instantiated the same way as Brad Wilson&#8217;s <a href="http://bradwilson.typepad.com/blog/2011/06/the-testable-object-pattern.html">Testable Object Pattern</a> with a static Create method.</p>
<p>The big difference from his pattern is that the system under test is a public Sut-property instead of using inheritance. The Create method instanciates mocks for the dependencies and creates the system under test with reflection, so less boilerplate code for you to write.</p>
<p>The problem I have with inheritance here is that you kind of pollute your class you wish to test with other stuff. And what I like about putting the system under test as property is you can add fluent methods to your wrapper class making the tests easier to read and understand.</p>
<p>For example:</p>
<pre class="brush: csharp; gutter: true">            //Arrange
            const string userName = &quot;Mats&quot;;
            const string emailAddress = &quot;mats@nospam.com&quot;;
            var userRepository = new Mock&lt;IUserRepository&gt;();
            var mailer = new Mock&lt;IMailer&gt;();
            var user = new Mock&lt;IUser&gt;();

            user.Setup(m =&gt; m.EmailAddress).Returns(emailAddress);
            userRepository.Setup(m =&gt; m.Get(userName)).Returns(() =&gt; user.Object);

            var sut = new ResetPassword(userRepository.Object, mailer.Object);

            //Act
            sut.Reset(userName);

            //Assert
            userRepository.Verify(d =&gt; d.Get(userName));
            mailer.Verify(d =&gt; d.SendMail(emailAddress));</pre>
<p><strong>Arrange is a bit noisy</strong>, and it&#8217;s not easy to see that the mock for user is not something the SUT is depending on, ResetPassword-class only depends on IUserRepository and IMailer.</p>
<p>Using the generic Testable object wrapper-class (called Tester) you then easily implement a wrapper with:</p>
<pre class="brush: csharp; gutter: true">    public class ResetPasswordTester :
        Tester&lt;ResetPasswordTester, ResetPassword, IUserRepository, IMailer&gt;
    {
        public Mock&lt;IUserRepository&gt; UserRepository { get { return Param1; } }
        public Mock&lt;IMailer&gt; Mailer { get { return Param2; } }

        public ResetPasswordTester WithUser(string userName, string emailAddress)
        {
            var user = new Mock&lt;IUser&gt;();
            user.Setup(m =&gt; m.EmailAddress).Returns(emailAddress);

            UserRepository.Setup(m =&gt; m.Get(userName)).Returns(() =&gt; user.Object);
            return this;
        }
    }</pre>
<p>The generic parameters are: the class itself (so Create-method returns correct instance), System under test (ResetPassword)  and one or more dependencies (IUserRepository, IMailer).</p>
<p>First dependency is first parameter, second dependency is second parameter. <strong>Tester automatically creates a instance of the system under test as a &#8220;Sut&#8221;-property</strong>.</p>
<p>Also added a fluent method (.WithUser(&#8230;) )that all tests for ResetPassword could use.</p>
<p>This gives you very <strong>clean and readable tests</strong>.</p>
<p>Another great effect is that if your class takes another dependency then you only have to change the signature of the wrapper and all tests using that wrapper work without any modification to the tests.</p>
<p>The first example could be refactored to look something like this:</p>
<pre class="brush: csharp; gutter: true">            //Arrange
            const string userName = &quot;Mats&quot;;
            const string emailAddress = &quot;mats@nospam.com&quot;;

            var tester = ResetPasswordTester
                .Create()
                .WithUser(userName, emailAddress);

            //Act
            tester.Sut.Reset(userName);

            //Assert
            tester.UserRepository.Verify(d=&gt;d.Get(userName));
            tester.Mailer.Verify(d =&gt; d.SendMail(emailAddress));</pre>
<p>Attached to this post is a simple implementation using Moq, and the dummy ResetPassword test class. Replacing Moq with something else like NSubstitute, FakeItEasy is extremely simple.</p>
<p><a href="http://www.matskarlsson.se/wp-content/uploads/2014/03/TestableObjectWrapper.zip">TestableObjectWrapper</a></p>
<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.matskarlsson.se/blog/testable-object-wrapper/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Solving setTimeout-problem using QUnit and SinonJS</title>
		<link>https://www.matskarlsson.se/blog/settimeout-problem-using-qunit-and-sinon</link>
					<comments>https://www.matskarlsson.se/blog/settimeout-problem-using-qunit-and-sinon#respond</comments>
		
		<dc:creator><![CDATA[Mats Karlsson]]></dc:creator>
		<pubDate>Wed, 22 May 2013 00:06:38 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Unit Test]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[QUnit]]></category>
		<category><![CDATA[SinonJS]]></category>
		<category><![CDATA[unit-test]]></category>
		<guid isPermaLink="false">http://www.matskarlsson.se/?p=65</guid>

					<description><![CDATA[Recently had a problem testing setTimout-callbacks when using the QUnit javascript testing framework and also adding SinonJS to the mix for faking xmlHttp-requests. Could not get the callback to fire. After a long time trying different examples using QUnit and SinonJS I finally got my facepalm moment and solved it. When adding the Sinon javascript and [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Recently had a problem testing setTimout-callbacks when using the <a title="QUnit JavaScript testing framework" href="http://qunitjs.com/">QUnit</a> javascript testing framework and also adding <a title="SinonJS test spies, stubs and mocks for JavaScript" href="http://sinonjs.org/">SinonJS</a> to the mix for faking xmlHttp-requests. Could not get the callback to fire. After a long time trying different examples using QUnit and SinonJS I finally got my <a href="http://en.wikipedia.org/wiki/Facepalm">facepalm </a>moment and solved it.</p>
<p>When adding the Sinon javascript and sinon-qunit script the QUnit script has a config section that enables useFakeTimers by default, so the clock wouldn&#8217;t tick/advance by default.</p>
<p>If you really want to use setTimeout the QUnit way (start/stop-functions), then your tests will have to wait until timeout elapses</p>
<p>A better way is to use sinon&#8217;s fake timers. a trivial example:</p>
<pre class="brush: javascript; gutter: true">test(&quot;test with useFakeTimers&quot;, function () {
  this.sandbox.useFakeTimers();

  setTimeout(function () {
    ok(true, &quot;timeout sucessfully called&quot;);
  }, 150);

  this.sandbox.clock.tick(200);
});</pre>
<p>and if you have useFakeTimers = true in your sinon-qunit-javascript you can even remove this.sandbox.useFakeTimers()</p>
<p>note: as of february 2010 the <a title="Latest version of sinon-qunit.js" href="https://raw.github.com/cjohansen/sinon-qunit/master/lib/sinon-qunit.js">source</a> at github has changed to have useFakeTimers disabled by default.</p>
<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.matskarlsson.se/blog/settimeout-problem-using-qunit-and-sinon/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Serialize .NET objects as camelCase JSON</title>
		<link>https://www.matskarlsson.se/blog/serialize-net-objects-as-camelcase-json</link>
					<comments>https://www.matskarlsson.se/blog/serialize-net-objects-as-camelcase-json#comments</comments>
		
		<dc:creator><![CDATA[Mats Karlsson]]></dc:creator>
		<pubDate>Sat, 02 Jun 2012 09:30:00 +0000</pubDate>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[JSON]]></category>
		<guid isPermaLink="false">/post/Serialize-NET-objects-as-camelCase-JSON.aspx</guid>

					<description><![CDATA[ASP.NET MVC is amazing how easy it is to serialize from a .NET POCO to JSON and the other way around using the model binder. But one thing I really don&#8217;t like is how serializing .NET objects to JSON returns the properties PascalCase. Net has PascalCase coding convention for properties and JavaScript uses camelCase. The [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>ASP.NET MVC is amazing how easy it is to serialize from a .NET <a title="Plain Old CLR Object" href="http://en.wikipedia.org/wiki/Plain_Old_CLR_Object">POCO</a> to JSON and the other way around using the model binder. But one thing I really don&#8217;t like is how serializing .NET objects to JSON returns the properties PascalCase.</p>
<p>Net has PascalCase coding convention for properties and JavaScript uses camelCase.</p>
<p>The solution is to use <a title="Json.NET on CodePlex" href="http://json.codeplex.com/">Json.NET</a> to serialize the objects (which will be included by default in Visual Studio 2012).</p>
<p>Continuing on the previous blog post you would then</p>
<p>Install Newtonsoft Json.NET using NuGet.</p>
<p>Modify the controller so instead of returning</p>
<pre class="brush: c-sharp; toolbar: false; auto-links: false;">return Json(new Dog { Name = &quot;Rambo&quot;, Age = 5 }, JsonRequestBehavior.AllowGet);</pre>
<p>you would create a JsonSerializerSettings, Serialize the object with JsonConvert and return the content with content type application/json</p>
<pre class="brush: c-sharp; toolbar: false; auto-links: false;">public ActionResult Load()
{
  var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
  var json = JsonConvert.SerializeObject(dog, Formatting.Indented, jsonSerializerSettings);

  return Content(json, &quot;application/json&quot;);
}</pre>
<p>which would give you</p>
<pre class="brush: js; toolbar: false; auto-links: false;">{
  &quot;name&quot;: &quot;Rambo&quot;,
  &quot;age&quot;: 5
}</pre>
<p>instead of</p>
<pre class="brush: js; toolbar: false; auto-links: false;">{
  &quot;Name&quot;: &quot;Rambo&quot;,
  &quot;Age&quot;: 5
}</pre>
<p class="brush: js; toolbar: false; auto-links: false;">Of course you would have to update your bindings and ViewModel-data to use camel case instead of pascal case.</p>
<p class="brush: js; toolbar: false; auto-links: false;">And when sending camelCase JSON to your controller the modelbinder automatically handles it and deserializes it correctly.</p>
<p class="brush: js; toolbar: false; auto-links: false;">I have included a updated example solution from the previous blog post where I have created a JsonCamelCaseResult inherited from ActionResult.</p>
<p class="brush: js; toolbar: false; auto-links: false;">Just:</p>
<pre class="brush: c-sharp; toolbar: false; auto-links: false;">return new JsonCamelCaseResult
              {
                   Data = new Dog { Name = &quot;Rambo&quot;, Age = 5 }, 
                   JsonRequestBehavior = JsonRequestBehavior.AllowGet
              };</pre>
<p><a href="/wp-content/uploads/2012/08/camelCaseJsonExample.zip">camelCaseJsonExample.zip (465.98 kb)</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.matskarlsson.se/blog/serialize-net-objects-as-camelcase-json/feed</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Automatic mapping with Knockout.js, the mapping plugin and ASP.NET MVC 3</title>
		<link>https://www.matskarlsson.se/blog/automatic-mapping-with-knockoutjs-the-mapping-plugin-and-aspnet-mvc-3</link>
					<comments>https://www.matskarlsson.se/blog/automatic-mapping-with-knockoutjs-the-mapping-plugin-and-aspnet-mvc-3#comments</comments>
		
		<dc:creator><![CDATA[Mats Karlsson]]></dc:creator>
		<pubDate>Thu, 03 May 2012 09:59:00 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Knockout.JS]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[knockout]]></category>
		<category><![CDATA[mvc3]]></category>
		<guid isPermaLink="false">/post/Automatic-mapping-with-Knockoutjs-the-mapping-plugin-and-ASPNET-MVC-3.aspx</guid>

					<description><![CDATA[Expected outcome Having a C# Dog class with name and age-properties. When the page loads, it automatically loads the dog using jQuery ajax (serialized as json) and creates a knockout viewmodel. ViewModel should automatically add properties from the C# model. The knockout ViewModel should be able to have extra computed methods for validating form for [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><img style="float: right;" src="/wp-content/uploads/2012/08/SimpleKnockoutExample.png" alt="" /></p>
<h3>Expected outcome</h3>
<ul>
<li>Having a C# Dog class with name and age-properties.</li>
<li>When the page loads, it automatically loads the dog using jQuery ajax (serialized as json) and creates a knockout viewmodel.</li>
<li>ViewModel should automatically add properties from the C# model.</li>
<li>The knockout ViewModel should be able to have extra computed methods for validating form for example.</li>
<li>The ViewModel should be able to save the dog using ajax.</li>
</ul>
<h3>Installing components</h3>
<p>Install <a title="Knockout.Mapping plugin on NuGet" href="http://www.nuget.org/packages/Knockout.Mapping">Knockout.Mapping</a> using <a title="NuGet Gallery" href="http://www.nuget.org/">NuGet</a>, this will automatically install <a href="http://knockoutjs.com/">Knockout</a>.</p>
<h3>Create Model</h3>
<p>First, create the dog, a simple C# plain object with two properties: Name and Age</p>
<pre class="brush: c-sharp; toolbar: false; auto-links: false;">public class Dog
{
    public string Name { get; set; }
    public int Age { get; set; }
}</pre>
<h3>Create MVC Controller</h3>
<p>Then create a empty DogController and add a empty Index method. The Load method just creates a simple instance of a dog and returns it as Json, and finally the Save method only accepts post data and just returns a formatted string in Json-format containing the updated Dog</p>
<pre class="brush: c-sharp; toolbar: false; auto-links: false;">public class DogController : Controller
{
    public virtual ActionResult Index()
    {
        return View();
    }

    public ActionResult Load()
    {
        return Json(new Dog { Name = &quot;Rambo&quot;, Age = 5 }, JsonRequestBehavior.AllowGet);
    }

    [HttpPost]
    public ActionResult Save(Dog dog)
    {
        return Json(new { Status = string.Format(&quot;Success, saved {0} with age: {1}&quot;, dog.Name, dog.Age) });
    }
}</pre>
<h3>Create View</h3>
<p>Create empty Index View and add script-references</p>
<pre class="brush: plain; toolbar: false; auto-links: false;">&lt;script src=&quot;@Url.Content(&quot;~/Scripts/knockout.js&quot;)&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;@Url.Content(&quot;~/Scripts/knockout-mapping-latest.js&quot;)&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;</pre>
<p>Then you add a form containing the knockout bindings bound to the <a title="Simple helloworld example on Knockout site " href="http://knockoutjs.com/examples/helloWorld.html">observables </a>on the ViewModel. Two input boxes data bound to Name and Age, the submit-action to &#8220;save&#8221;, a function on the JavsScript ViewModel, and finally data-bind the submit button so it&#8217;s enabled only if the model is valid.</p>
<pre class="brush: plain; toolbar: false; auto-links: false;">&lt;form method=&quot;POST&quot; data-bind=&quot;submit: save&quot;&gt;
    &lt;div&gt;Name:&lt;/div&gt;
    &lt;div&gt;&lt;input type=&quot;text&quot; data-bind=&quot;value: Name&quot; /&gt;&lt;/div&gt;

    &lt;div&gt;Age:&lt;/div&gt;
    &lt;div&gt;&lt;input type=&quot;text&quot; data-bind=&quot;value: Age&quot; /&gt;&lt;/div&gt;

    &lt;div&gt;&lt;input type=&quot;submit&quot; value=&quot;Save&quot; data-bind=&quot;enable: isValid()&quot; /&gt;&lt;/div&gt;
&lt;/form&gt;</pre>
<h3>Create ViewModel</h3>
<p>Create a class in JavaScript, taking JSON data to be mapped as parameter, and add isValid as a <a href="http://knockoutjs.com/documentation/computedObservables.html">computed</a> property and finally a save function that posts the JSON-data back to the DogController&#8217;s Save method.</p>
<pre class="brush: js; toolbar: false; auto-links: false;">var ViewModel = function (data) {
	var self = this;
	ko.mapping.fromJS(data, {}, self);

	self.isValid = ko.computed(function () {
		return self.name().length &gt; 0;
	});

	self.save = function () {
		$.ajax({
			url: &quot;Knockout2/Save&quot;,
			type: &quot;post&quot;,
			contentType: &quot;application/json&quot;,
			data: ko.mapping.toJSON(self),
			success: function (response) {
				alert(response.Status);
			}
		});
	};
};</pre>
<h3>Load initial data</h3>
<p>Finally you add a JavaScript <a title="document ready" href="http://api.jquery.com/ready/">document ready</a> handler that loads the initial data. Place it below the ViewModel.</p>
<pre class="brush: js; toolbar: false; auto-links: false;">$(function () {
    $.getJSON(&quot;Dog/Load&quot;, null, function (data) {
        ko.applyBindings(new ViewModel(data));
    });
});</pre>
<h3>Conclusion</h3>
<p>This is probably not the best way, and of course there are lots of stuff you should do. For example, move javascript references to bottom of page, validate the postback and more. But I tried to keep the example as simple as possible.</p>
<p>Download the project here:</p>
<p><a href="/wp-content/uploads/2012/08/SimpleKnockoutExample.zip">SimpleKnockoutExample.zip (456.44 kb)</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.matskarlsson.se/blog/automatic-mapping-with-knockoutjs-the-mapping-plugin-and-aspnet-mvc-3/feed</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>Create Html.DropdownListFor without magic strings</title>
		<link>https://www.matskarlsson.se/blog/create-htmldropdownlistfor-without-magic-strings</link>
					<comments>https://www.matskarlsson.se/blog/create-htmldropdownlistfor-without-magic-strings#respond</comments>
		
		<dc:creator><![CDATA[Mats Karlsson]]></dc:creator>
		<pubDate>Tue, 20 Sep 2011 03:45:00 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<guid isPermaLink="false">/post/Create-HtmlDropdownListFor-without-magic-strings.aspx</guid>

					<description><![CDATA[Using magic strings are bad practice. Changes could lead to code compiling but containing lots of errors (appearing during runtime). And refactoring your code is a lot harder if you have to globally search and replace. Using dropdown lists with ASP.NET MVC has a Html-helper that wants you to use magic strings. Having a Category [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Using magic strings are bad practice. Changes could lead to code compiling but containing lots of errors (appearing during runtime). And refactoring your code is a lot harder if you have to globally search and replace.</p>
<p>Using dropdown lists with ASP.NET MVC has a Html-helper that wants you to use magic strings. Having a Category class:</p>
<pre class="brush: csharp; toolbar: false; auto-links: false;">    public class Category
    {
        public int CategoryId { get; set; }
        public string Name { get; set; }
    }</pre>
<p>And a viewmodel:</p>
<pre class="brush: csharp; toolbar: false; auto-links: false;">    public class DropdownViewModel
    {
        public int CategoryId { get; set; }
        public Category[] Categories { get; set; }
    }</pre>
<p>&nbsp;</p>
<p>You would then use the html-helper like this:</p>
<pre class="brush: csharp; toolbar: false; auto-links: false;">    public static class ExtensionMethods
    {
        public static IEnumerable&lt;SelectListItem&gt; ToSelectList&lt;TItem, TValue&gt;(this IEnumerable&lt;TItem&gt; enumerable, Func&lt;TItem, TValue&gt; value, Func&lt;TItem, string&gt; text, string defaultText = null, string defaultValue = null)
        {
            var itms = enumerable.Select(f =&gt; new SelectListItem { Text = text(f), Value = value(f).ToString() }).ToList();
            if (defaultText != null)
                itms.Insert(0, new SelectListItem { Text = defaultText, Value = defaultValue ?? &quot;0&quot; });
            return itms;
        }
    }</pre>
<p>Now it&#8217;s easy to just use lambdas and, this little extension method has a couple of overloads.</p>
<pre class="brush: csharp; toolbar: false; auto-links: false;">Html.DropDownListFor(m =&gt; m.CategoryId, 
    Model.Categories.ToSelectList(f =&gt; f.CategoryId, f =&gt; f.Name))</pre>
<p>Usage is really easy, just use the extension method on the Array you wish to create a dropdown items from.</p>
<p>Now your code is refactor safe</p>
<p>First parameter: Selected item in model</p>
<p>Second parameter: Id/value-item (generic TValue, so you can use for example int&#8217;s without calling ToString()</p>
<p>Third parameter: Text to display for each item in dropdown</p>
<p>Fourth parameter(optional): Empty default-text (first item in dropdown), uses value &#8220;0&#8221; if fifth parameter isn&#8217;t supplied</p>
<p>Fifth parameter(optional): Empty default-value</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.matskarlsson.se/blog/create-htmldropdownlistfor-without-magic-strings/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Creating and intitializing ArrayList in one line</title>
		<link>https://www.matskarlsson.se/blog/creating-and-intitializing-arraylist-in-one-line</link>
					<comments>https://www.matskarlsson.se/blog/creating-and-intitializing-arraylist-in-one-line#comments</comments>
		
		<dc:creator><![CDATA[Mats Karlsson]]></dc:creator>
		<pubDate>Sun, 10 Oct 2010 05:10:00 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<guid isPermaLink="false">/post/Creating-and-intitializing-ArrayList-in-one-line.aspx</guid>

					<description><![CDATA[There are multiple ways of creating a ArrayList and adding a couple of items to it.&#160; The usual way to do it: List&#60;String&#62; normal = new ArrayList&#60;String&#62;(); normal.add(&#34;one&#34;); normal.add(&#34;two&#34;); normal.add(&#34;three&#34;); Or you could use the double braces. The inner pair of braces creates a anonymous innner class List&#60;String&#62; doubleBraces = new ArrayList&#60;String&#62;() {{ add(&#34;one&#34;); add(&#34;two&#34;); [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>There are multiple ways of creating a ArrayList and adding a couple of items to it.&nbsp;</p>
<p>The usual way to do it:</p>
<pre class="brush: java;">List&lt;String&gt; normal = new ArrayList&lt;String&gt;();
		normal.add(&quot;one&quot;);
		normal.add(&quot;two&quot;);
		normal.add(&quot;three&quot;);</pre>
<p>Or you could use the double braces. The inner pair of braces creates a anonymous innner class</p>
<pre class="brush: java;">List&lt;String&gt; doubleBraces = new ArrayList&lt;String&gt;() {{
				add(&quot;one&quot;);
				add(&quot;two&quot;);
				add(&quot;three&quot;);
		}};</pre>
<p>But I prefer to use a small static method that uses generics and varargs to accomplish the same thing.</p>
<pre class="brush: java;">public class Simple {

	public static &lt;T&gt; ArrayList&lt;T&gt; listOf(T... elements) {
		ArrayList&lt;T&gt; list = new ArrayList&lt;T&gt;();
		for (T element : elements) {
			list.add(element);
		}
		return list;
	}
}</pre>
<p>And to use it you just write:</p>
<pre class="brush: java;">List&lt;String&gt; simple = Simple.listOf(&quot;one&quot;, &quot;two&quot;, &quot;three&quot;);</pre>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.matskarlsson.se/blog/creating-and-intitializing-arraylist-in-one-line/feed</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk
Page Caching using disk: enhanced

 Served from: www.matskarlsson.se @ 2024-02-12 02:18:07 by W3 Total Cache -->